Find the tuples containing the given element from a list of tuples in Python


A list can have tuples as its elements. In this article we will learn how to identify those tuples which contain a specific search element which is a string.

With in and condition

We can design a follow with in condition. After in we can mention the condition or a combination of conditions.

Example

 Live Demo

listA = [('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
test_elem = 'Mon'
#Given list
print("Given list:\n",listA)
print("Check value:\n",test_elem)
# Uisng for and if
res = [item for item in listA
   if item[0] == test_elem and item[1] >= 2]
# printing res
print("The tuples satisfying the conditions:\n ",res)

Output

Running the above code gives us the following result −

Given list:
[('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
Check value:
Mon
The tuples satisfying the conditions:
[('Mon', 3), ('Mon', 2)]

With filter

We use the filter function along with Lambda function. In the filter condition we use the the in operator to check for the presence of the element in the tuple.

Example

 Live Demo

listA = [('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
test_elem = 'Mon'
#Given list
print("Given list:\n",listA)
print("Check value:\n",test_elem)
# Uisng lambda and in
res = list(filter(lambda x:test_elem in x, listA))
# printing res
print("The tuples satisfying the conditions:\n ",res)

Output

Running the above code gives us the following result −

Given list:
[('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
Check value:
Mon
The tuples satisfying the conditions:
[('Mon', 3), ('Mon', 2)]

Updated on: 04-Jun-2020

473 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements