
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python – Filter immutable rows representing Dictionary Keys from Matrix
When it is required to filter immutable rows representing dictionary keys from a matrix, a list comprehension and the ‘isinstance’ method can be used.
Below is a demonstration of the same −
Example
my_list = [[24, 15, [32, 33, 12]], ["pyt", 8, (14, 54)], [{15:24}, 13, "fun"], [True, "cool"]] print("The list is :") print(my_list) my_result = [row for row in my_list if all(isinstance(element, int) or isinstance(element, bool) or isinstance(element, float) or isinstance(element, tuple) or isinstance(element, str) for element in row)] print("The result is :") print(my_result)
Output
The list is : [[24, 15, [32, 33, 12]], ['pyt', 8, (14, 54)], [{15: 24}, 13, 'fun'], [True, 'cool']] The result is : [['pyt', 8, (14, 54)], [True, 'cool']]
Explanation
A list of list is defined and is displayed on the console.
A list comprehension is used to iterate over the elements, and the ‘isinstance’ method is used to check if an element belong to a specific data type.
If yes, it is stored in a list, and is assigned to a variable.
This is displayed as the output on the console.
- Related Articles
- Why must dictionary keys be immutable in Python?
- Python Extract specific keys from dictionary?
- Python - Filter the negative values from given dictionary
- Python – Filter Sorted Rows
- Properties of Dictionary Keys in Python
- Python - Cumulative Mean of Dictionary keys
- How to create Python dictionary from list of keys and values?
- Filter the rows – Python Pandas
- Python – Filter rows with only Alphabets from List of Lists
- How does Python dictionary keys() Method work?
- Python dictionary with keys having multiple inputs
- Append Dictionary Keys and Values (In order ) in dictionary using Python
- Python – Filter rows with required elements
- Python – Filter Rows with Range Elements
- Python – Filter rows without Space Strings

Advertisements