- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
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