Open In App

Python | Check if element is present in tuple of tuples

Last Updated : 08 May, 2023
Improve
Improve
Like Article
Like
Save
Share
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.



Similar Reads

Python | Check if element is present in tuple
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 ou
7 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 | Find the tuples containing the given element from a list of tuples
Given a list of tuples, the task is to find all those tuples containing the given element, say n. Examples: Input: n = 11, list = [(11, 22), (33, 55), (55, 77), (11, 44)] Output: [(11, 22), (11, 44)] Input: n = 3, list = [(14, 3),(23, 41),(33, 62),(1, 3),(3, 3)] Output: [(14, 3), (1, 3), (3, 3)] There are multiple ways we can find the tuples contai
6 min read
Python program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple
The task is to write a Python Program to sort a list of tuples in increasing order by the last element in each tuple. Input: [(1, 3), (3, 2), (2, 1)] Output: [(2, 1), (3, 2), (1, 3)] Explanation: sort tuple based on the last digit of each tuple. Methods #1: Using sorted(). Sorted() method sorts a list and always returns a list with the elements in
7 min read
Getting an Element from Tuple of Tuples in Python
Tuples in Python are versatile data structures that allow you to store and organize collections of elements. When dealing with tuples of tuples, accessing specific elements becomes essential for effective data manipulation. In this article, we'll explore some different methods to retrieve elements from a tuple of tuples: using slicing, employing a
2 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 | Remove duplicate tuples from list of tuples
Given a list of tuples, Write a Python program to remove all the duplicated tuples from the given list. Examples: Input : [(1, 2), (5, 7), (3, 6), (1, 2)] Output : [(1, 2), (5, 7), (3, 6)] Input : [('a', 'z'), ('a', 'x'), ('z', 'x'), ('a', 'x'), ('z', 'x')] Output : [('a', 'z'), ('a', 'x'), ('z', 'x')] Method #1 : List comprehension This is a naive
5 min read
Python | Remove tuples from list of tuples if greater than n
Given a list of a tuple, the task is to remove all the tuples from list, if it's greater than n (say 100). Let's discuss a few methods for the same. Method #1: Using lambda STEPS: Initialize a list of tuples: ini_tuple = [('b', 100), ('c', 200), ('c', 45), ('d', 876), ('e', 75)]Print the initial list: print("intial_list", str(ini_tuple))Define the
6 min read
Python | Remove tuples having duplicate first value from given list of tuples
Given a list of tuples, the task is to remove all tuples having duplicate first values from the given list of tuples. Examples: Input: [(12.121, 'Tuple1'), (12.121, 'Tuple2'), (12.121, 'Tuple3'), (923232.2323, 'Tuple4')] Output: [(12.121, 'Tuple1'), (923232.2323, 'Tuple4')]Input: [('Tuple1', 121), ('Tuple2', 125), ('Tuple1', 135), ('Tuple4', 478)]
7 min read
Practice Tags :
three90RightbarBannerImg