Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Check if element is present in tuple
Next article icon

Python | Check if element is present in tuple of tuples

Last Updated : 08 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 tests one by one if the element is present as the tuple element. If the element is present, true is returned else false is returned. 

Python3
# Python3 code to demonstrate # test for values in tuple of tuple # using any()  # initializing tuple of tuple test_tuple = (("geeksforgeeks", "gfg"), ("CS_Portal", "best"))  # printing tuple print("The original tuple is " + str(test_tuple))  # using any() # to test for value in tuple of tuple if (any('geeksforgeeks' in i for i in test_tuple)):     print("geeksforgeeks is present") else:     print("geeksforgeeks is not present") 

Output
The original tuple is (('geeksforgeeks', 'gfg'), ('CS_Portal', 'best')) geeksforgeeks is present

Time complexity: The time complexity of this program is O(nm) where n is the length of the outer tuple and m is the length of the inner tuple. 

Auxiliary space: The program uses a constant amount of auxiliary space to store the test tuple and the string to search for.

Method #2: Using itertools.chain() The chain function tests for all the intermediate tuples for the desired values and then returns true if the required value is present in any of the tuples searched. 

Python3
# Python3 code to demonstrate # test for values in tuple of tuple # using itertools.chain() import itertools  # initializing tuple of tuple test_tuple = (("geeksforgeeks", "gfg"), ("CS_Portal", "best"))  # printing tuple print("The original tuple is " + str(test_tuple))  # using itertools.chain() # to test for value in tuple of tuple if ('geeksforgeeks' in itertools.chain(*test_tuple)):     print("geeksforgeeks is present") else:     print("geeksforgeeks is not present") 

Output
The original tuple is (('geeksforgeeks', 'gfg'), ('CS_Portal', 'best')) geeksforgeeks is present

The time complexity of the code is O(n), where n is the total number of elements in all the tuples.

The auxiliary space complexity of the code is O(1), because we are not using any extra space to store data. 

Method #3: Using list comprehension

Python3
test_tuple = (("geeksforgeeks", "gfg"), ("CS_Portal", "best"))  ele="geeksforgeeks" x=[ele for i in test_tuple if ele in i]  print(["yes" if x else "no"]) 

Output
['yes']

Time Complexity: O(n), where n is the length of the list 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list 

Method #4: Using enumerate function

Python3
test_tuple = (("geeksforgeeks", "gfg"), ("CS_Portal", "best"))  ele="geeksforgeeks" x=[ele for a,i in enumerate(test_tuple) if ele in i]  print(["yes" if x else "no"]) 

Output
['yes']

The time complexity is O(n), where n is the length of the input tuple test_tuple.

The auxiliary space complexity of the code is O(1).

Method #5: Using lambda function

Python3
test_tuple = (("geeksforgeeks", "gfg"), ("CS_Portal", "best"))  ele="geeksforgeeks"  x=list(filter(lambda i: (i in test_tuple),test_tuple))  print(["yes" if x else "no"]) 

Output
['yes']

Method: Using "in" operator 

Python3
test_tuple = (("geeksforgeeks", "gfg"), ("CS_Portal", "best"))  ele="geeksforgeeks" ;a=[] for i in test_tuple:   if ele in i:     a.append(ele) print(["yes" if a else "no"]) 

Output
['yes']

Method: Using countOf function 

Python3
import operator as op test_tuple = (("geeksforgeeks", "gfg"), ("CS_Portal", "best"))  ele="geeksforgeeks"   x=[j for i in test_tuple for j in i] print("yes" if op.countOf(x,ele)>0 else "no") 

Output
yes

Method : Using map and lambda:

Approach is to use a combination of the map function and the lambda to check if an element is present in a tuple of tuples. This can be done as follows:

Python3
# Initialize the tuple of tuples test_tuple = (("geeksforgeeks", "gfg"), ("CS_Portal", "best"))  # Check if the element is present in any of the tuples if any(map(lambda t: "geeksforgeeks" in t, test_tuple)):     print("geeksforgeeks is present") else:     print("geeksforgeeks is not present") #This code is contributed by Edula Vinay Kumar Reddy 

Output
geeksforgeeks is present

The map function applies a function to each element of an iterable and returns a new iterable with the results. In this case, the lambda function checks if the element is present in the tuple using the in operator, and the any function returns True if any of the elements in the resulting iterable is True.

This approach has a time complexity of O(n), where n is the number of tuples in the input tuple of tuples. It has a space complexity of O(1), since it only uses a constant amount of additional space.


Next Article
Python - Check if element is present in tuple
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python - Check if element is present in tuple
    We are given a tuple and our task is to find whether given element is present in tuple or not. For example x = (1, 2, 3, 4, 5) and we need to find if 3 is present in tuple so that in this case resultant output should be True. Using in Operatorin operator checks if an element is present in a tuple by
    2 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.
    6 min read
  • Test if all elements are present in list-Python
    The task of testing if all elements are present in a list in Python involves checking whether every item in a target list exists within a reference list. For example, given two lists a = [6, 4, 8, 9, 10] and b = [4, 6, 9], the task is to confirm that all elements in list b are also found in list a.
    3 min read
  • Python | Filter tuples according to list element presence
    Sometimes, while working with records, we can have a problem in which we have to filter all the tuples from a list of tuples, which contains atleast one element from a list. This can have applications in many domains working with data. Let's discuss certain ways in which this task can be performed.
    8 min read
  • How to Check if Tuple is empty in Python ?
    A Tuple is an immutable sequence, often used for grouping data. You need to check if a tuple is empty before performing operations. Checking if a tuple is empty is straightforward and can be done in multiple ways. Using the built-in len() will return the number of elements in a tuple and if the tupl
    2 min read
  • Python | Combining tuples in list of tuples
    Sometimes, we might have to perform certain problems related to tuples in which we need to segregate the tuple elements to combine with each element of complex tuple element( such as list ). This can have application in situations we need to combine values to form a whole. Let's discuss certain ways
    7 min read
  • Python - Test if greater than preceding element in Tuple List
    Given list of tuples, check if preceding element is smaller than the current element for each element in Tuple list. Input : test_list = [(5, 1), (4, 9), (3, 5)] Output : [[False, False], [False, True], [False, True]] Explanation : First element always being False, Next element is checked for greate
    9 min read
  • Python | Check if any element occurs n times in given list
    Given a list, the task is to find whether any element occurs 'n' times in given list of integers. It will basically check for the first element that occurs n number of times. Examples: Input: l = [1, 2, 3, 4, 0, 4, 3, 2, 1, 2], n = 3 Output : 2 Input: l = [1, 2, 3, 4, 0, 4, 3, 2, 1, 2, 1, 1], n = 4
    5 min read
  • Python - Check if Tuple contains only K elements
    Sometimes, while working with Python tuples, we can have a problem in which we need to test if any tuple contains elements from set K elements. This kind of problem is quite common and have application in many domains such as web development and day-day programming. Let's discuss certain ways in whi
    3 min read
  • Python - Test if all elements in list are of same type
    When working with lists in Python, there are times when we need to ensure that all the elements in the list are of the same type or not. This is particularly useful in tasks like data analysis where uniformity is required for calculations. In this article, we will check several methods to perform th
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences