Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Python – Extract String elements from Mixed Matrix
When it is required to extract string elements from mixed matrix, a list comprehension and the ‘isinstance’ method is used.
Example
Below is a demonstration of the same −
my_list = [[35, 66, 31], ["python", 13, "is"], [15, "fun", 14]]
print("The list is :")
print(my_list)
my_result = [element for index in my_list for element in index if isinstance(element, str)]
print("The result is :")
print(my_result)
Output
The list is : [[35, 66, 31], ['python', 13, 'is'], [15, 'fun', 14]] The result is : ['python', 'is', 'fun']
Explanation
A list of list is defined and displayed on the console.
A list comprehension is used to iterate over the elements in the list.
The ‘isinstance’ method is used to check if the elements in the list of list belong to a specific type.
If yes, it is converted to a list and is assigned to a variable.
This list is displayed as the output on the console.
Advertisements
