When it is required to extract particular data type rows, the list comprehension, the ‘isinstance’ method, and the ‘all’ operator are used.
Below is a demonstration of the same −
Example
my_list = [[14,35, "Will"], [12, 26, 17], ["p", "y", "t"], [29, 40, 21]] print("The list is :") print(my_list) my_data_type = int my_result = [row for row in my_list if all(isinstance(element, my_data_type) for element in row)] print("The result is :") print(my_result)
Output
The list is : [[14, 35, 'Will'], [12, 26, 17], ['p', 'y', 't'], [29, 40, 21]] The result is : [[12, 26, 17], [29, 40, 21]]
Explanation
A list of list is defined and is displayed on the console.
The data type is defined.
A list iteration is used to iterate over the list.
The ‘all’ operator and the ‘isinstance’ method is sued to check if the elements in the list belong to a specific data type.
If yes, it is added to a list, and assigned to a variable.
This is displayed as the output on the console.