Open In App

Python – Filter immutable rows representing Dictionary Keys from Matrix

Improve
Improve
Like Article
Like
Save
Share
Report

Given Matrix, extract all the rows which has elements which have all elements which can be represented as dictionary key, i.e immutable.

Input : test_list = [[4, 5, [2, 3, 2]], [“gfg”, 1, (4, 4)], [{5:4}, 3, “good”], [True, “best”]] 
Output : [[‘gfg’, 1, (4, 4)], [True, ‘best’]] 
Explanation : All elements in tuples are immutable.

Input : test_list = [[4, 5, [2, 3, 2]], [“gfg”, 1, (4, 4), [3, 2]], [{5:4}, 3, “good”], [True, “best”]] 
Output : [[True, ‘best’]] 
Explanation : All elements in tuples are immutable. 

Method #1 : Using all() + isinstance()

In this, we check for all elements to be of the instance of immutable data types, rows that return True for all elements, is filtered.

Python3




# Python3 code to demonstrate working of
# Filter Dictionary Key Possible Element rows
# Using all() + isinstance()
 
# initializing list
test_list = [[4, 5, [2, 3, 2]], ["gfg", 1, (4, 4)], [{5: 4}, 3, "good"], [
    True, "best"]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# checking for each immutable data type
res = [row for row in test_list if all(isinstance(ele, int) or isinstance(ele, bool)
                                       or isinstance(ele, float) or isinstance(ele, tuple)
                                       or isinstance(ele, str) for ele in row)]
 
# printing result
print("Filtered rows : " + str(res))


Output

The original list is : [[4, 5, [2, 3, 2]], ['gfg', 1, (4, 4)], [{5: 4}, 3, 'good'], [True, 'best']]
Filtered rows : [['gfg', 1, (4, 4)], [True, 'best']]

Time Complexity: O(n*m)
Auxiliary Space: O(k)

Method #2 : Using filter() + lambda + isinstance() + all()

In this, we perform task of filtering using filter() + lambda function, rest all functionalities are performed as above method.

Python3




# Python3 code to demonstrate working of
# Filter Dictionary Key Possible Element rows
# Using filter() + lambda + isinstance() + all()
 
# initializing list
test_list = [[4, 5, [2, 3, 2]], ["gfg", 1, (4, 4)], [{5: 4}, 3, "good"], [
    True, "best"]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# checking for each immutable data type
# filtering using filter()
res = list(filter(lambda row: all(isinstance(ele, int) or isinstance(ele, bool)
                                  or isinstance(ele, float) or isinstance(ele, tuple)
                                  or isinstance(ele, str) for ele in row), test_list))
 
# printing result
print("Filtered rows : " + str(res))


Output

The original list is : [[4, 5, [2, 3, 2]], ['gfg', 1, (4, 4)], [{5: 4}, 3, 'good'], [True, 'best']]
Filtered rows : [['gfg', 1, (4, 4)], [True, 'best']]

Time Complexity: O(n), where n is the length of the input list. This is because we’re using the built-in filter() + lambda + isinstance() + all() which all has a time complexity of O(n) in the worst case.
Auxiliary Space: O(n), where n is the length of the input list as we’re using additional space other than the input list itself. 

Method #3: Using itertools.filterfalse() method

Python3




# Python3 code to demonstrate working of
# Filter Dictionary Key Possible Element rows
import itertools
# initializing list
test_list = [[4, 5, [2, 3, 2]], ["gfg", 1, (4, 4)], [{5: 4}, 3, "good"], [
    True, "best"]]
 
# printing original list
print("The original list is : " + str(test_list))
 
 
res = list(itertools.filterfalse(lambda row: not all(isinstance(ele, int) or isinstance(ele, bool)
                                  or isinstance(ele, float) or isinstance(ele, tuple)
                                  or isinstance(ele, str) for ele in row), test_list))
 
# printing result
print("Filtered rows : " + str(res))


Output

The original list is : [[4, 5, [2, 3, 2]], ['gfg', 1, (4, 4)], [{5: 4}, 3, 'good'], [True, 'best']]
Filtered rows : [['gfg', 1, (4, 4)], [True, 'best']]

Time Complexity: O(N*N)
Auxiliary Space: O(N*N)

Method #4 : Using all()+type() methods

Python3




# Python3 code to demonstrate working of
# Filter Dictionary Key Possible Element rows
 
# initializing list
test_list = [[4, 5, [2, 3, 2]], ["gfg", 1, (4, 4)], [{5: 4}, 3, "good"], [
    True, "best"]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# checking for each immutable data type
res = [row for row in test_list if all(type(ele) is int or type(ele) is bool
                                    or type(ele) is float or type(ele) is tuple
                                    or type(ele) is  str for ele in row)]
 
# printing result
print("Filtered rows : " + str(res))


Output

The original list is : [[4, 5, [2, 3, 2]], ['gfg', 1, (4, 4)], [{5: 4}, 3, 'good'], [True, 'best']]
Filtered rows : [['gfg', 1, (4, 4)], [True, 'best']]

Time Complexity: O(N*N)
Auxiliary Space: O(N*N)

Method 5: Filtering a nested list based on the types of its elements.

The idea is to filtering the rows of a nested list (test_list) such that only the rows whose elements are of specific types (int, bool, float, tuple, and str) are kept.

  • Define a set of allowed data types (allowed_types).
  • Initialize an empty list (res) to hold the filtered rows.
  • Loop over each row in the original list (test_list).For each row, loop over its elements (elem) and check if their type is in the set of allowed types. If an element is not of an allowed type, set a flag (is_allowed) to False and break out of the inner loop.
  • If is_allowed is still True after checking all elements of the row, add the row to the filtered list (res).
  • Print the filtered list (res).

Below is the implementation:

Python3




# Python3 code to demonstrate working of
# Filter Dictionary Key Possible Element rows
# Using a for loop and a set of allowed data types
 
# initializing list
test_list = [[4, 5, [2, 3, 2]], ["gfg", 1, (4, 4)], [{5: 4}, 3, "good"], [
    True, "best"]]
 
# set of allowed data types
allowed_types = {int, bool, float, tuple, str}
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing an empty list for filtered rows
res = []
 
# looping over rows and checking if each element is of an allowed type
for row in test_list:
    is_allowed = True
    for elem in row:
        if type(elem) not in allowed_types:
            is_allowed = False
            break
    if is_allowed:
        res.append(row)
 
# printing result
print("Filtered rows : " + str(res))


Output

The original list is : [[4, 5, [2, 3, 2]], ['gfg', 1, (4, 4)], [{5: 4}, 3, 'good'], [True, 'best']]
Filtered rows : [['gfg', 1, (4, 4)], [True, 'best']]

Time complexity: O(n*m), where n is the number of rows in the nested list and m is the maximum number of elements in a row. 
Auxiliary space: O(k), where k is the number of rows that pass the filter (i.e., the length of the filtered list res).

Method 6:Using numpy:

Algorithm :

  1. Iterate over each row in the input list test_list.
  2. For each row, iterate over each element in the row.
  3. Check if the element is an instance of any of the allowed data types (int, bool, float, tuple, str) using the isinstance() function.
  4. If all elements in the row are instances of an allowed data type, add the row to the list of filtered rows.
  5. Return the list of filtered rows.

Python3




import numpy as np
# initializing list
test_list = [[4, 5, [2, 3, 2]], ["gfg", 1, (4, 4)], [{5: 4}, 3, "good"], [True, "best"]]
# printing original list
print("The original list is : " + str(test_list))
res = list(filter(lambda row: np.all([isinstance(ele, (int, bool, float, tuple, str)) for ele in row]), test_list))
# printing result
print("Filtered rows : " + str(res))
#This code is contributed by Jyothi Pinjala.


Output:

The original list is : [[4, 5, [2, 3, 2]], [‘gfg’, 1, (4, 4)], [{5: 4}, 3, ‘good’], [True, ‘best’]]
Filtered rows : [[‘gfg’, 1, (4, 4)], [True, ‘best’]]

The time complexity : O(nm), where n is the number of rows in test_list and m is the maximum number of elements in a row. This is because we need to iterate over each row and each element in each row to determine if the row should be included in the filtered list.

The auxiliary space : O(k), where k is the number of valid rows in the filtered list. This is because we are creating a new list to store the filtered rows, which will be at most the same length as the input list. However, if all rows are valid, the space complexity could be O(nm) if we create a copy of the input list to store the filtered rows



Last Updated : 21 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads