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
Selected Reading
Python – Check if any list element is present in Tuple
When it is required to check if any list element is present in a tuple or not, Python provides several approaches. We can use simple iteration, the any() function, or set intersection for efficient checking.
Using Simple Iteration
This approach uses a loop to check each list element against the tuple ?
my_tuple = (14, 35, 27, 99, 23, 89, 11)
print("The tuple is :")
print(my_tuple)
my_list = [16, 27, 88, 99]
print("The list is :")
print(my_list)
my_result = False
for element in my_list:
if element in my_tuple:
my_result = True
break
print("The result is :")
if my_result:
print("At least one element from the list is present in the tuple")
else:
print("No element from the list is present in the tuple")
The tuple is : (14, 35, 27, 99, 23, 89, 11) The list is : [16, 27, 88, 99] The result is : At least one element from the list is present in the tuple
Using any() Function
The any() function provides a more concise and Pythonic solution ?
my_tuple = (14, 35, 27, 99, 23, 89, 11)
my_list = [16, 27, 88, 99]
result = any(element in my_tuple for element in my_list)
print(f"Tuple: {my_tuple}")
print(f"List: {my_list}")
print(f"Any element present: {result}")
Tuple: (14, 35, 27, 99, 23, 89, 11) List: [16, 27, 88, 99] Any element present: True
Using Set Intersection
For larger datasets, set intersection provides optimal performance ?
my_tuple = (14, 35, 27, 99, 23, 89, 11)
my_list = [16, 27, 88, 99]
tuple_set = set(my_tuple)
list_set = set(my_list)
has_common = bool(tuple_set & list_set)
common_elements = tuple_set & list_set
print(f"Tuple: {my_tuple}")
print(f"List: {my_list}")
print(f"Has common elements: {has_common}")
print(f"Common elements: {common_elements}")
Tuple: (14, 35, 27, 99, 23, 89, 11)
List: [16, 27, 88, 99]
Has common elements: True
Common elements: {99, 27}
Comparison
| Method | Time Complexity | Best For |
|---|---|---|
| Simple Iteration | O(n*m) | Small datasets, readable code |
any() |
O(n*m) | Pythonic, concise solution |
| Set Intersection | O(n+m) | Large datasets, need common elements |
Conclusion
Use any() for clean, readable code when checking if any list element exists in a tuple. For large datasets or when you need the actual common elements, set intersection provides better performance.
Advertisements
