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
-
Economics & Finance
Python – Extract Particular data type rows
When working with lists of lists in Python, you may need to extract rows that contain only elements of a particular data type. This can be achieved using list comprehension combined with the isinstance() method and all() operator.
Syntax
result = [row for row in data if all(isinstance(element, data_type) for element in row)]
Example
Here's how to extract rows containing only integers from a mixed-type list ?
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)
The list is: [[14, 35, 'Will'], [12, 26, 17], ['p', 'y', 't'], [29, 40, 21]] The result is: [[12, 26, 17], [29, 40, 21]]
Extract String Rows
You can also extract rows containing only strings ?
mixed_data = [[1, 2, 3], ["apple", "banana"], [4.5, 6.7], ["cat", "dog", "bird"]]
string_rows = [row for row in mixed_data if all(isinstance(element, str) for element in row)]
print("String rows:")
print(string_rows)
String rows: [['apple', 'banana'], ['cat', 'dog', 'bird']]
How It Works
List comprehension iterates through each row in the main list
isinstance(element, data_type)checks if each element matches the specified typeall()ensures that every element in the row matches the data typeOnly rows where all elements match are included in the result
Multiple Data Types
You can also filter for multiple data types using a tuple ?
data = [[1, 2], ["a", "b"], [1.5, 2.5], [True, False]]
# Extract rows with only numbers (int or float)
numeric_rows = [row for row in data if all(isinstance(element, (int, float)) for element in row)]
print("Numeric rows:")
print(numeric_rows)
Numeric rows: [[1, 2], [1.5, 2.5], [True, False]]
Conclusion
Use list comprehension with isinstance() and all() to filter rows by data type. This approach is efficient and readable for extracting specific data patterns from nested lists.
