Check if element is present in tuple of tuples in Python


Python Tuples can be nested. We can have a tuple whose elements are also tuples. In this article we will see how to find out if a given value is present as an element in a tuple of tuples.

With any

The any function can be used to check if a given value is present as an element in any of the subtuples that are present in the tuple with help of for loop. We put the entire condition for checking in an if and else clause.

Example

 Live Demo

Atuple = [('Mon',10),('Tue',8),('Wed',8),('Thu',5)]

#Given tuple
print("Given tuple: ",Atuple)

# Use any
if any('Tue' in i for i in Atuple):
   print("present")
else :
   print("Not present")


if any(3 in i for i in Atuple):
   print("present")
else :
   print("Not present")

Output

Running the above code gives us the following result −

Given tuple: [('Mon', 10), ('Tue', 8), ('Wed', 8), ('Thu', 5)]
present
Not present

With itertools.chain

The chain function in itertools module returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. So we use it with the given tuple expanding all its content and checking for the presence of the required value using the if clause.

Example

 Live Demo

import itertools
Atuple = (('Mon',10),('Tue',8),('Wed',8),('Thu',5))

#Given tuple
print("Given tuple: ",Atuple)

# Use chain
if ('Wed' in itertools.chain(*Atuple)) :
print("Wed is present")
else :
   print("Wed is not present")


if (11 in itertools.chain(*Atuple)) :
   print("11 is present")
else :
   print("11 is not present")

Output

Running the above code gives us the following result −

Given tuple: (('Mon', 10), ('Tue', 8), ('Wed', 8), ('Thu', 5))
Wed is present
11 is not present

Updated on: 13-May-2020

908 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements