How to filter list elements in list of tuples

Tuple Python

In this article, we are going to learn about, How to filter list elements in list of tuples,a list for a given element in the list of tuples. There are many uses cases for this while working on huge data samples in Data science and Data analysis. We get the raw data and then to make this data clean and ready for some analysis we manipulate by using the filtering of unwanted data.

Filtering a list by removing the unwanted data is used widely in those use cases. So we will learn different techniques available to Data analysts.

We will do this by using different techniques available in Python. So let us begin with the techniques to implement this.

1. Using List comprehension with in operator


The first approach which we are going Using List comprehension with IN operator and passing a condition using if statement to filter upon.

Here is an example in which we are using this technique.

Program Example

listoftuple = [(1,2,'C#'),('Pyth',4),('Pyth',5,6),(7,8,),('Pyth',6)]

item = 'Pyth'

output = [element for element in listoftuple
   if element[0] == item] 

#filltering the list of tuple

print('fliterring list of tuples =\n',output)

Output

fliterring list of tuples =
 [('Pyth', 4), ('Pyth', 5, 6), ('Pyth', 6)]

2. Using lambda and list


The second approach to get the desired filter results is by using a lambda function.

As you can see in the example below we are going to use the lambda function to do the job.

Program Example

listoftuple = [(1,2,'C#'),('Pyth',4),('Pyth',5,6),(7,8,),('Pyth',6)]

item = 'Pyth'

output = list(filter(lambda x:item in x, listoftuple))

#filltering the list of tuple

print('fliterring list of tuples =\n',output)

Output

fliterring list of tuples =
 [('Pyth', 4), ('Pyth', 5, 6), ('Pyth', 6)]

3.Using set() function


The third technique we are going to use is by using the set() function. Set() functions help us in filtering the list of tuples. We pass a list to this function and get the desired results.

Program Example

listoftuple = [(1,2,'C#'),(3,4),(1,5,6),(7,8,)]

reslist= [6,7,1,'C#']

filter_set = set(reslist)

#filltering the list of tuple

filtertuple = [tuple for tuple in listoftuple if tuple[0] in filter_set]

print('fliterring list of tuples =\n',filtertuple)

Output

fliterring list of tuples =
 [(1, 2, 'C#'), (1, 5, 6), (7, 8)]

4. List comprehension


The last technique that we are going to learn in this article is by using list comprehension with any() operator in python.

Here is an example to understand this.

Program Example

listoftuple = [(1,2,'C#'),('Pyth',4),('Pyth',5,6),(7,8,),('Pyth',6)]

item = ['Pyth',5,6,1]

output = filterlist = [tupleitem for tupleitem in listoftuple if any(j in tupleitem for j in item)] 

#filltering the list of tuple

print('fliterring list of tuples =\n',output)

Output

fliterring list of tuples =
 [(1, 2, 'C#'), ('Pyth', 4), ('Pyth', 5, 6), ('Pyth', 6)]