Open In App

Python | Check if element is present in tuple

Last Updated : 02 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with data, we can have a problem in which we need to check if the data we are working with has a particular element. Let’s discuss certain ways in which this task can be performed. 

Method #1: Using loop 

This is a brute force method to perform this task. In this, we iterate through the tuple and check each element if it’s our, if found we return True. 

Python3




# Python3 code to demonstrate working of
# Check if element is present in tuple
# using loop
 
# initialize tuple
test_tup = (10, 4, 5, 6, 8)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# initialize N
N = 6
 
# Check if element is present in tuple
# using loop
res = False
for ele in test_tup:
    if N == ele:
        res = True
        break
 
# printing result
print("Does tuple contain required value ? : " + str(res))


Output

The original tuple : (10, 4, 5, 6, 8)
Does tuple contain required value ? : True

Time complexity: O(n)
Auxiliary space: O(n), where n is the length of the tuple.

Method #2: Using in operator 

It is used to perform this task. It is a one-liner and recommended to perform this task. 

Python3




# Python3 code to demonstrate working of
# Check if element is present in tuple
# Using in operator
 
# initialize tuple
test_tup = (10, 4, 5, 6, 8)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# initialize N
N = 6
 
# Check if element is present in tuple
# Using in operator
res = N in test_tup
 
# printing result
print("Does tuple contain required value ? : " + str(res))


Output

The original tuple : (10, 4, 5, 6, 8)
Does tuple contain required value ? : True

Method 3: Using list comprehension method 

Python3




t = (10, 4, 5, 6, 8)
n = 6
x = [i for i in t if i == n]
print(["yes" if x else "no"])


Output

['yes']

Method 4: Using lambda function 

Python3




t = (10, 4, 5, 6, 8)
n = 6
x = tuple(filter(lambda i: (i == n), t))
print(["yes" if x else "no"])


Output

['yes']

Method 5: Using the enumerate function

Python3




t = ('10', '4', '5', '6', '8')
n = 6
x = [int(i) for i in t if int(i) == n]
print(["yes" if x else "no"])


Output

['yes']

Method 6: Using count() method

Python3




# Python3 code to demonstrate working of
# Check if element is present in tuple
# using loop
 
# initialize tuple
test_tup = (10, 4, 5, 6, 8)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# initialize N
N = 6
 
# Check if element is present in tuple
# using loop
res = False
if(test_tup.count(N) >= 1):
    res = True
# printing result
print("Does tuple contain required value ? : " + str(res))


Output

The original tuple : (10, 4, 5, 6, 8)
Does tuple contain required value ? : True

Method 7: Using try/except and index:

Python3




# Python3 code to demonstrate working of
# Check if element is present in tuple
# using loop
 
# initialize tuple
test_tup = (10, 4, 5, 6, 8)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# initialize N
N = 6
 
# Check if element is present in tuple
# using loop
res = False
try:
    test_tup.index(N)
    res = True
except ValueError:
    pass
# printing result
print("Does tuple contain required value ? : " + str(res))
# this code is contributed by edula vinay kumar reddy


Output

The original tuple : (10, 4, 5, 6, 8)
Does tuple contain required value ? : True

Time complexity: O(n)
Auxiliary Space : O(1)

Method 8: Using recursion

Python3




# Python3 code to demonstrate working of
# Check if element is present in tuple
# using recursion method
 
# defining recursion function
 
 
def value_present(start, lst, value):
    if start == len(lst):  # base condition
        return False
    if lst[start] == value:  # checking lst[start] is value or not
        return True
    return value_present(start+1, lst, value)  # recursive call
 
 
# initialize tuple
test_tup = (10, 4, 5, 6, 8)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# initialize N
N = 6
 
res = value_present(0, test_tup, N)
print("Does tuple contain required value ? : " + str(res))
# this code is contributed by tvsk


Output

The original tuple : (10, 4, 5, 6, 8)
Does tuple contain required value ? : True

Time complexity: O(n)
Auxiliary Space : O(n)

Method 9: reduce function from functools module:

  1. Import the reduce function from functools module.
  2. Define the tuple of strings named ‘t’ and an integer named ‘n’.
  3. Define a lambda function that takes an accumulator and an element and checks if the element is equal to n.
  4. If the element is equal to n, then append the integer version of the element to the accumulator, otherwise return the accumulator as it is.
  5. Pass this lambda function as the function argument to the reduce() function, along with the iterable ‘t’ and an empty list as the initial value of the accumulator.
  6. The reduce() function returns a list of integers that contain all the elements of ‘t’ that are equal to ‘n’.
  7. Check if this list is empty or not.
  8. If the list is not empty, print ‘yes’, otherwise print ‘no’.

Python3




from functools import reduce
 
t = ('10', '4', '5', '6', '8')
n = 6
# printing original tuple
print("The original tuple : " + str(t))
  
x = reduce(lambda acc, i: acc + [int(i)] if int(i) == n else acc, t, [])
 
if x:
  print("True")
else:
  print("false")
  #This code is contributed by Jyothi pinjala.


Output

True

Time complexity: O(n), where n is the length of the tuple t. This is because the reduce() function iterates through the entire tuple once.
Auxiliary Space: O(k), where k is the number of integers in the tuple t that are equal to n. This is because the reduce() function creates a new list with only the integers that are equal to n.
has a context menu.

Method 10: Using numpy:

1. Initialize the tuple of tuples.
2. Convert the tuple of tuples to a NumPy array using np.array().
3. Check if “geeksforgeeks” is in the NumPy array.
4. If “geeksforgeeks” is present, print “geeksforgeeks is present”. Otherwise, print “geeksforgeeks is not present”.
 

Python3




import numpy as np
 
# Initialize the tuple of tuples
test_tuple = (("geeksforgeeks", "gfg"), ("CS_Portal", "best"))
 
# Convert the tuple of tuples to a 2D NumPy array
test_array = np.array(test_tuple)
 
# Check if the element is present in any of the tuples
if "geeksforgeeks" in test_array:
    print("geeksforgeeks is present")
else:
    print("geeksforgeeks is not present")
#This code is contributed by Rayudu.


Output:

geeksforgeeks is present

Time Complexity:

Converting the tuple of tuples to a NumPy array has a time complexity of O(n), where n is the total number of elements in the tuple of tuples.
Checking if a string is present in a 1D array has a time complexity of O(n), where n is the length of the 1D array.
Therefore, the overall time complexity of the NumPy implementation is O(n).
Auxiliary Space:

Converting the tuple of tuples to a NumPy array has a space complexity of O(n), where n is the total number of elements in the tuple of tuples.
Therefore, the overall space complexity of the NumPy implementation is also O(n).

Method 11: Using while loop and in operator: 

Approach: 

  • Initialize the test_list. 
  • Initialize the boolean variable that contains True. 
  • While loop checks the condition for the boolean variable and the presence of the element in the list.
  • If the element is present in the list negate the value boolean value. 
  •  Print the result. 

Python




# Python3 code to demonstrate working of
# Check if element is present in tuple
# using loop
 
# initialize tuple
test_tup = (10, 4, 5, 6, 8)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# initialize N
N = 6
temp = True
 
# Check if element is present in tuple
# using loop
while temp and N in test_tup:
    temp  = False
 
# printing result
print("Does tuple contain required value ? : " + str(not temp))


Output

The original tuple : (10, 4, 5, 6, 8)
Does tuple contain required value ? : True

Time Complexity: O(n), where n is the length of the list
Auxiliary Space: O(n)



Similar Reads

Python | Check if element is present in tuple of tuples
Sometimes the data that we use is in the form of tuples and often we need to look into the nested tuples as well. The common problem that this can solve is looking for missing data or na value in data preprocessing. Let's discuss certain ways in which this can be performed. Method #1: Using any() any function is used to perform this task. It just t
4 min read
Python - Check if any list element is present in Tuple
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 v
6 min read
Python | Sort tuple list by Nth element of tuple
Sometimes, while working with Python list, we can come across a problem in which we need to sort the list according to any tuple element. These must be a generic way to perform the sort by particular tuple index. This has a good utility in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using sort(
8 min read
Python | Replace tuple according to Nth tuple element
Sometimes, while working with data, we might have a problem in which we need to replace the entry in which a particular entry of data is matching. This can be a matching phone no, id etc. This has it's application in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + enumerate() This task
8 min read
Python - Raise elements of tuple as power to another tuple
Sometimes, while working with records, we can have a problem in which we may need to perform exponentiation, i.e power of tuples. This problem can occur in day-day programming. Let’s discuss certain ways in which this task can be performed. Method #1: Using zip() + generator expression The combination of above functions can be used to perform this
8 min read
Python - Convert Tuple String to Integer Tuple
Interconversion of data is a popular problem developer generally deal with. One can face a problem to convert tuple string to integer tuple. Let's discuss certain ways in which this task can be performed. Method #1 : Using tuple() + int() + replace() + split() The combination of above methods can be used to perform this task. In this, we perform th
7 min read
Python - Convert Tuple to Tuple Pair
Sometimes, while working with Python Tuple records, we can have a problem in which we need to convert Single tuple with 3 elements to pair of dual tuple. This is quite a peculiar problem but can have problems in day-day programming and competitive programming. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ('A'
10 min read
Python - Flatten tuple of List to tuple
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have listed as their constituent elements. This kind of problem is common in data domains such as Machine Learning. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ([5], [6], [3], [8]) O
7 min read
Python Program to Convert Tuple Matrix to Tuple List
Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]] Output : [(4, 10), (5, 13)] Explanation : All co
8 min read
Python program to convert Set into Tuple and Tuple into Set
Let's see how to convert the set into tuple and tuple into the set. For performing the task we are use some methods like tuple(), set(), type(). tuple(): tuple method is used to convert into a tuple. This method accepts other type values as an argument and returns a tuple type value.set(): set method is to convert other type values to set this meth
7 min read
Practice Tags :