Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 from a list of tuples using different methods.
Using List Comprehension with Condition
We can use list comprehension with a conditional statement to filter tuples that contain the target element ?
listA = [('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
test_elem = 'Mon'
# Given list
print("Given list:")
print(listA)
print("Check value:")
print(test_elem)
# Using list comprehension with condition
res = [item for item in listA if item[0] == test_elem]
# printing result
print("The tuples containing the element:")
print(res)
Given list:
[('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
Check value:
Mon
The tuples containing the element:
[('Mon', 3), ('Mon', 2)]
Using filter() with Lambda Function
We can use the filter() function along with a lambda function. The in operator checks for the presence of the element anywhere in the tuple ?
listA = [('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
test_elem = 'Mon'
# Given list
print("Given list:")
print(listA)
print("Check value:")
print(test_elem)
# Using lambda and filter with 'in' operator
res = list(filter(lambda x: test_elem in x, listA))
# printing result
print("The tuples containing the element:")
print(res)
Given list:
[('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
Check value:
Mon
The tuples containing the element:
[('Mon', 3), ('Mon', 2)]
Using a Simple Loop
For better readability, you can use a simple for loop to iterate through the list and check each tuple ?
listA = [('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
test_elem = 'Mon'
# Given list
print("Given list:")
print(listA)
print("Check value:")
print(test_elem)
# Using simple loop
res = []
for item in listA:
if test_elem in item:
res.append(item)
# printing result
print("The tuples containing the element:")
print(res)
Given list:
[('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
Check value:
Mon
The tuples containing the element:
[('Mon', 3), ('Mon', 2)]
Comparison of Methods
| Method | Readability | Performance | Best For |
|---|---|---|---|
| List Comprehension | High | Fast | Simple filtering |
| filter() with lambda | Medium | Fast | Functional programming style |
| Simple Loop | Highest | Moderate | Complex logic or beginners |
Conclusion
Use list comprehension for simple and fast filtering of tuples. The filter() function works well for functional programming approaches, while simple loops offer the best readability for complex conditions.
