How does the \'in\' operator work on a tuple in Python?

Python offers the 'in' operator to verify that a value is present in a tuple. This operator is very useful when you are looking for items in a collection without requiring loops or complex logic.

In this article, we will discuss the 'in' operator and how it works on tuples in Python. Before moving on, we will first discuss tuples.

Tuples in Python are an immutable sequence, and they are created by placing a sequence of values separated by a 'comma', with or without the use of parentheses for data grouping. Tuples can have any number of elements and any type of data (like strings, integers, lists, etc.).

The "in" Operator on a Tuple

The 'in' operator checks if the object is present in the tuple. It returns True if a sequence with the given value is present in the object and False if it is not present.

Syntax

element in tuple_name

Example 1: Basic Usage with Strings

The following example shows how to check if an element is present in the tuple ?

my_tuple = ('Tutorialspoint', 'is', 'the', 'best', 'platform', 'to', 'learn', 'new', 'skills')
print("Tutorialspoint" in my_tuple)
print("HelloWorld" in my_tuple)

In the above example, the string "Tutorialspoint" is present in the tuple, so the in operator returns True. But the string "HelloWorld" is not present in the tuple, so it returns False.

True
False

Example 2: Using with Numbers

Following is another example showing the usage of the 'in' operator with numeric values ?

my_tuple = (5, 1, 8, 3, 7)
print(8 in my_tuple) 
print(0 in my_tuple)
True 
False

Example 3: Using with String Elements

In this example, we will check if a string is present in the tuple or not ?

my_tuple = ('apple', 'banana', 'cherry')
print('banana' in my_tuple)
print('orange' in my_tuple)
True
False

Example 4: Using with Complex Objects (Lists)

In this example, we will check if a list is present in the tuple or not ?

my_tuple = ([1, 2], [3, 4], [5, 6])
print([1, 2] in my_tuple)
print([7, 8] in my_tuple)
True
False

Example 5: Using with Dictionaries

In this example, we will check if a dictionary is present in the tuple or not ?

my_tuple = ({'name': 'Shreya'}, {'age': 22}, {'city': 'Gurgaon'})
print({'name': 'Shreya'} in my_tuple)
print({'name': 'Parul'} in my_tuple)
True
False

Key Points

  • The 'in' operator performs exact match comparison
  • It returns a boolean value: True or False
  • Works with any data type stored in tuples
  • For complex objects like lists or dictionaries, the entire object must match exactly
  • Time complexity is O(n) where n is the number of elements in the tuple

Conclusion

The 'in' operator provides a simple and efficient way to check membership in tuples. It works with all data types and performs exact matching, making it ideal for boolean checks without writing loops.

Updated on: 2026-03-24T19:07:32+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements