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 – Filter immutable rows representing Dictionary Keys from Matrix
When working with matrices (lists of lists) in Python, you may need to filter rows containing only immutable data types that can serve as dictionary keys. This involves checking if all elements in each row are immutable types like int, str, tuple, bool, or float.
Understanding Immutable Types
In Python, immutable types can be used as dictionary keys because they are hashable. These include:
int − Integer numbers
str − String values
tuple − Ordered collections (if containing only immutable elements)
bool − Boolean values
float − Floating-point numbers
Mutable types like list, dict, and set cannot be used as dictionary keys.
Example
Let's filter a matrix to keep only rows containing immutable elements ?
matrix = [[24, 15, [32, 33, 12]], ["pyt", 8, (14, 54)], [{15: 24}, 13, "fun"], [True, "cool"]]
print("The matrix is :")
print(matrix)
# Filter rows with only immutable elements
immutable_rows = [row for row in matrix if all(isinstance(element, (int, bool, float, tuple, str)) for element in row)]
print("The filtered result is :")
print(immutable_rows)
The matrix is :
[[24, 15, [32, 33, 12]], ['pyt', 8, (14, 54)], [{15: 24}, 13, 'fun'], [True, 'cool']]
The filtered result is :
[['pyt', 8, (14, 54)], [True, 'cool']]
How It Works
The solution uses list comprehension with the isinstance() function:
Outer loop: Iterates through each row in the matrix
Inner condition: Uses
all()to check if every element in the row is an immutable typeType checking:
isinstance(element, (int, bool, float, tuple, str))checks multiple types at onceFiltering: Only rows where all elements are immutable are included
Alternative Approach Using a Function
For better readability, you can create a helper function ?
def is_immutable(element):
"""Check if an element is of immutable type"""
return isinstance(element, (int, bool, float, tuple, str))
def filter_immutable_rows(matrix):
"""Filter rows containing only immutable elements"""
return [row for row in matrix if all(is_immutable(element) for element in row)]
matrix = [[24, 15, [32, 33, 12]], ["pyt", 8, (14, 54)], [{15: 24}, 13, "fun"], [True, "cool"]]
result = filter_immutable_rows(matrix)
print("Filtered rows:", result)
Filtered rows: [['pyt', 8, (14, 54)], [True, 'cool']]
Why This Filtering Is Useful
This technique is particularly useful when:
Preparing data to create dictionaries where row elements will be keys
Ensuring data integrity before hash-based operations
Cleaning datasets that mix mutable and immutable types
Conclusion
Use list comprehension with isinstance() and all() to filter matrix rows containing only immutable elements. This ensures the filtered data can be safely used as dictionary keys or in hash-based operations.
