Skip to content
Related Articles

Related Articles

Python – Check if any list element is present in Tuple

View Discussion
Improve Article
Save Article
  • Last Updated : 01 Sep, 2022
View Discussion
Improve Article
Save Article

Given a tuple, check if any list element is present in it.

Input : test_tup = (4, 5, 10, 9, 3), check_list = [6, 7, 10, 11] 
Output : True 
Explanation : 10 occurs in both tuple and list.

Input : test_tup = (4, 5, 12, 9, 3), check_list = [6, 7, 10, 11] 
Output : False 
Explanation : No common elements. 

Method #1: Using loop

In this, we keep a boolean variable, keeping record of all elements, if found, then returns True, else False.

Python3




# Python3 code to demonstrate working of
# Check if any list element is present in Tuple
# Using loop
 
# initializing tuple
test_tup = (4, 5, 7, 9, 3)
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# initializing list
check_list = [6, 7, 10, 11]
 
res = False
for ele in check_list:
     
    # checking using in operator
    if ele in test_tup :
        res = True
        break
 
# printing result
print("Is any list element present in tuple ? : " + str(res))

Output

The original tuple is : (4, 5, 7, 9, 3)
Is any list element present in tuple ? : True

Method #2: Using any()

This returns True, if any element of list is found in tuple, test using in operator.

Python3




# Python3 code to demonstrate working of
# Check if any list element is present in Tuple
# Using any()
 
# initializing tuple
test_tup = (4, 5, 7, 9, 3)
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# initializing list
check_list = [6, 7, 10, 11]
 
# generator expression is used for iteration
res = any(ele in test_tup for ele in check_list)
 
# printing result
print("Is any list element present in tuple ? : " + str(res))

Output

The original tuple is : (4, 5, 7, 9, 3)
Is any list element present in tuple ? : True

Method #3: Using list comprehension

Python3




test_tup = (4, 5, 7, 9, 3)
check_list = [6, 7, 10, 11]
x=["true" for i in check_list if i in test_tup]
print(x)

Output

['true']

Method #4: Using enumerate function

Python3




test_tup = (4, 5, 7, 9, 3)
check_list = [6, 7, 10, 11]
x=["true" for a,i in enumerate(check_list) if i in test_tup]
print(x)

Output

['true']

Method #5: Using lambda function

Python3




test_tup = (4, 5, 7, 9, 3)
check_list = [6, 7, 10, 11
x=list(filter(lambda i:(i in check_list),test_tup))
print(["true" if x else "false"])

Output

['true']

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!