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 −


 Live Demo

my_list = [[24, 15, [32, 33, 12]], ["pyt", 8, (14, 54)], [{15:24}, 13, "fun"], [True, "cool"]]

print("The list is :")

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 :")


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']]


  • 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.