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 Operator
in operator checks if an element is present in a tuple by iterating through its items. It returns True if the element is found and False otherwise making it a simple and efficient membership check.
x = (1, 2, 3, 4, 5)
# Check if the element '3' is present in the tuple
res = 3 in x
print(res)
Output
True
Explanation:
- in operator checks if the element 3 is present in tuple x.
- If element is found it returns True; otherwise it returns False
Using index()
index() method returns the position of the first occurrence of an element in a tuple. If the element is not found it raises a ValueError so it’s often used with exception handling.
t = (1, 2, 3, 4, 5)
try:
index = t.index(3)
res = True # If '3' is found
except ValueError:
res = False # If '3' is not found
print(res)
Output
True
Explanation:
- t.index(3) searches for the element 3 in the tuple t and returns its index if found.
- If element is not found a ValueError is raised which is caught to set result to False.
Using a Loop
Using a loop we can iterate through each element of the tuple to check for a match. If target element is found we return True otherwise we return False after checking all elements.
t = (1, 2, 3, 4, 5)
ele = 3
res = False
for item in t:
# Check if the current element matches
if item == ele:
res = True
break
print(res)
Output
True
Explanation:
- Loop checks each element in the tuple for equality with ele. If a match is found res is set to True.
- Break statement stops further iteration once the element is found improving efficiency.