CBSE Class 11 Computer Science Question 62 of 114

Tuples — Question 14

Back to all questions
14
Question

Question 14

Is the working of in operator and tuple.index( ) same ?

Answer

Both in operator and tuple.index( ) can be used to search for an element in the tuple but their working it is not exactly the same.
The "in" operator returns true or false whereas tuple.index() searches for a element for the first occurrence and returns its position. If the element is not found in tuple or the index function is called without passing any element as a parameter then tuple.index( ) raises an error:

For Example:-
tuple = (1, 3, 5, 7, 9)
print(3 in tuple) ⇒ True
print(4 in tuple) ⇒ False
print(tuple.index(3)) ⇒ 1
print(tuple.index(2)) ⇒ Error

ValueError: tuple.index(x): x not in tuple 

print(tuple.index()) ⇒ Error

TypeError: index expected at least 1 argument, got 0 
Answer