Open In App

Python | Filter tuples according to list element presence

Last Updated : 10 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with records, we can have a problem in which we have to filter all the tuples from a list of tuples, which contains atleast one element from a list. This can have applications in many domains working with data. Let’s discuss certain ways in which this task can be performed. 

Method #1: Using list comprehension Using list comprehension is brute force method to perform this task in a shorthand. In this, we just check for each tuple and check if it contains any element from the target list. 

Step-by-step approach :

  • Create a new list called res.
  • For each tuple tup in the list test_list, do the following:
    a. Check if any element from the tar_list is present in the tuple tup.
    b. If it is present, append the tuple tup to the res list.
  • Print the filtered tuples list res with a message saying “Filtered tuple from list are: “.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Filter tuples according to list element presence
# using list comprehension
 
# initialize list of tuple
test_list = [(1, 4, 6), (5, 8), (2, 9), (1, 10)]
 
# initialize target list
tar_list = [6, 10]
 
# printing original tuples list
print("The original list : " + str(test_list))
 
# Filter tuples according to list element presence
# using list comprehension
res = [tup for tup in test_list if any(i in tup for i in tar_list)]
 
# printing result
print("Filtered tuple from list are : " + str(res))


Output : 

The original list : [(1, 4, 6), (5, 8), (2, 9), (1, 10)]
Filtered tuple from list are : [(1, 4, 6), (1, 10)]

Time complexity: O(n * m), where n is the number of tuples and m is the number of elements in the target list.
Auxiliary space: O(1), as only a constant amount of extra space is used to store the filtered list.

Method #2 : Using set() + list comprehension Above approach can be optimized by converting the containers to a set() reducing duplicates and performing a & operation to fetch the desired records. 

Python3




# Python3 code to demonstrate working of
# Filter tuples according to list element presence
# using set() + list comprehension
 
# initialize list of tuple
test_list = [(1, 4, 6), (5, 8), (2, 9), (1, 10)]
 
# initialize target list
tar_list = [6, 10]
 
# printing original tuples list
print("The original list : " + str(test_list))
 
# Filter tuples according to list element presence
# using set() + list comprehension
res = [tup for tup in test_list if (set(tar_list) & set(tup))]
 
# printing result
print("Filtered tuple from list are : " + str(res))


Output : 

The original list : [(1, 4, 6), (5, 8), (2, 9), (1, 10)]
Filtered tuple from list are : [(1, 4, 6), (1, 10)]

Time complexity: O(n*m), where n is the length of test_list and m is the length of tar_list.
Auxiliary space: O(k), where k is the length of the resulting filtered list.

Method #3 : Using find() method

Python3




# Python3 code to demonstrate working of
# Filter tuples according to list element presence
 
# initialize list of tuple
test_list = [(1, 4, 6), (5, 8), (2, 9), (1, 10)]
 
# initialize target list
tar_list = [6, 10]
 
# printing original tuples list
print("The original list : " + str(test_list))
 
# Filter tuples according to list element presence
re=[]
for i in test_list:
    re.append("".join(list(map(str,i))))
res=[]
for i in tar_list:
    for j in range(0,len(re)):
        if(re[j].find(str(i))!=-1):
            res.append(test_list[j])
 
# printing result
print("Filtered tuple from list are : " + str(res))


Output

The original list : [(1, 4, 6), (5, 8), (2, 9), (1, 10)]
Filtered tuple from list are : [(1, 4, 6), (1, 10)]

Time complexity: O(n*m*k), where n is the length of test_list, m is the maximum length of a tuple in test_list, and k is the length of tar_list.
Auxiliary space: O(n), where n is the length of test_list.

Method #4 : Using filter() and lambda function
This is another approach to perform this task where the filter() method is used along with a lambda function to check if an element from the target list is present in the tuple or not.

Step-by-step approach:

  • First, a list of tuples called test_list is defined with four tuples inside it.
  • A target list called tar_list is also defined with two elements.
  • The original list of tuples is printed using print(“The original list : ” + str(test_list)).
  • A lambda function is defined inside the filter() function. This lambda function takes one argument x, which represents each tuple in the test_list. Inside the lambda function, the any() function is used to check if any element of the tar_list is present in the current tuple x. The lambda function returns True or False based on the result of the any() function.
  • The filter() function applies the lambda function to each tuple in the test_list and filters out the tuples for which the lambda function returns False. The resulting filtered tuples are stored in the variable res.
  • The filtered tuple from the list is printed using print(“Filtered tuple from list are : ” + str(res)).

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Filter tuples according to list element presence
# using filter() and lambda function
 
# initialize list of tuple
test_list = [(1, 4, 6), (5, 8), (2, 9), (1, 10)]
 
# initialize target list
tar_list = [6, 10]
 
# printing original tuples list
print("The original list : " + str(test_list))
 
# Filter tuples according to list element presence
# using filter() and lambda function
res = list(filter(lambda x: any(i in x for i in tar_list), test_list))
 
# printing result
print("Filtered tuple from list are : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original list : [(1, 4, 6), (5, 8), (2, 9), (1, 10)]
Filtered tuple from list are : [(1, 4, 6), (1, 10)]

Time complexity: O(n)
Auxiliary Space: O(n)

Method 5:Using for loop and a conditional statement

Ues a for loop instead of the filter() function. The any() function is used to check if any element in the tuple is present in the target list. If this condition is true, the tuple is added to the result list.

step-by-step approach :

Step 1: Initialize a list called “test_list” containing multiple tuples.

Step 2: Initialize another list called “tar_list” containing some elements.

Step 3: Initialize an empty list called “res” that will store the filtered tuples.

Step 4: Use a for loop to iterate through each tuple in the “test_list”.

Step 5: Use the any() function along with a nested for loop to check if any element of the tuple is present in the “tar_list”.

Step 6: If any element of the tuple is present in the “tar_list”, append that tuple to the “res” list.

Step 7: Print the filtered tuple list.

Python3




test_list = [(1, 4, 6), (5, 8), (2, 9), (1, 10)]
tar_list = [6, 10]
 
res = []
for tup in test_list:
    if any(elem in tar_list for elem in tup):
        res.append(tup)
 
print("Filtered tuple from list are : " + str(res))


Output

Filtered tuple from list are : [(1, 4, 6), (1, 10)]

Time complexity: O(n*m), where n is the number of tuples in the test_list and m is the maximum number of elements in a tuple. 
Auxiliary space: O(k), where k is the number of tuples that match the condition. 

Method #6: Using filter() and generator expression

Step-by-step approach:

  • Initialize the test_list and tar_list with the same values as mentioned in the problem statement.
  • Define a lambda function that checks if any element of the tuple is present in tar_list.
  • Use filter() function with the lambda function as the first argument and test_list as the second argument to filter out the tuples that do not contain any element of tar_list.
  • Convert the filtered output from step 3 into a list using the list() function.
  • Print the resulting filtered tuples using print() function.

Below is the implementation of the above approach:

Python3




test_list = [(1, 4, 6), (5, 8), (2, 9), (1, 10)]
tar_list = [6, 10]
 
# define lambda function
check_tar = lambda tup: any(elem in tar_list for elem in tup)
 
# use filter() function
filtered_list = list(filter(check_tar, test_list))
 
# print the resulting tuples
print("Filtered tuple from list are : " + str(filtered_list))


Output

Filtered tuple from list are : [(1, 4, 6), (1, 10)]

Time complexity: O(n*m), where n is the length of test_list and m is the length of tar_list.
Auxiliary space: O(k), where k is the number of tuples that contain at least one element from tar_list



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads