When it is required to extract rows with complex data types, the ‘isinstance’ method and list comprehension are used.
Example
Below is a demonstration of the same
my_list = [[13, 1,35], [23, [44, 54], 85], [66], [75, (81, 2), 29, 7]] my_result = [row for row in my_list if any(isinstance(element, list) or isinstance(element, tuple) or isinstance(element, dict) or isinstance(element, set) for element in row)] print("The list is :") print(my_list) print("The resultant list is :") print(my_result)
Output
The list is : [[13, 1, 35], [23, [44, 54], 85], [66], [75, (81, 2), 29, 7]] The resultant list is : [[23, [44, 54], 85], [75, (81, 2), 29, 7]]
Explanation
A list of list is defined and is displayed on the console.
A list comprehension is used to iterate over the list and see if the element belongs to the ‘list’ type using the ‘isinstance’ method.
This is assigned to a variable.
This is displayed as the output on the console.