To check if a tuple contains an element, use the membership “in” operator. It returns True if an element exists, and False otherwise.
The syntax is simple: if element in tuple, where element is the one we need to find in the tuple.
main_tuple = (11, 19, "Image_gen4", 3.14)
print("Image_gen4" in main_tuple)
# Output: True
print("world" in main_tuple)
# Output: False
In the above code, we checked if the “Image_gen4” string element exists in the tuple.
The element does exist, and hence the “in” operator returns True.
The “world” element does not exist, so it returns False.
The time complexity is O(n) since we search linearly through the tuple. Therefore, it depends on the total number of elements (n) in the tuple.
What about frequency membership checks?
If your current task requires frequent element checks in the tuple and contains hashable elements (numbers, strings, or tuples of hashables, etc.), you can convert the tuple into a set and then use the “in” operator.
But you will have a question: Why do we need to convert in the first place? Well, set lookup is speedy and has a time complexity of O(1). So, it would be easy to search in a set rather than a tuple.
The initial conversion to a set is O(n), which requires time and memory. After the conversion, you can check as many times as you want without losing time.
main_tuple = (11, 19, "Image_gen4", 3.14)
# Converting tuple to set
tuple_set = set(main_tuple)
print("Image_gen4" in tuple_set)
# Output: True
print("world" in tuple_set)
# Output: False
Handling unhashable elements
If you are working with a tuple that contains unhashable elements like lists, you can’t convert the tuple into a set. In that scenario, use the “in” operator to check the element’s existence.
main_tuple = ([21, 19], ["Image_gen4", "Flux"], 3.14) print([21, 19] in main_tuple) # Output: True print(["mid", "Flux"] in main_tuple) # Output: False
Checking for NaN (Not a Number)
NaN is an exceptional floating value represented by undefined or unrepresentable numerical results. Since nobody knows what NaN is, NaN != NaN evaluates to True.
The “in” operator does not work for checking NaN values because two NaNs are different values.
To solve this tricky problem, we can use math.isnan() method with a generator expression.
A generator expression efficiently iterates through a tuple. Using the isinstance() method, it applies the math.nan() function to only floating-point numbers.
For each floating-point element, math.isnan() returns True if the input element is NaN and False otherwise.
import math
tuple_nan = (float('nan'), 1, 2)
has_nan = any(math.isnan(x) for x in tuple_nan if isinstance(x, float))
print(has_nan)
# Output: True
That’s all!

