
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Now we will use the 'in' operator to check if the object is present in the tuple. The 'in' operator returns "True" if a sequence with the given value is present in the object and "False" if it is not present.
Example
The 'in' operator in Python helps you to loop over all of the members of a collection (such as a list or a tuple) and see if any of them are equal to the given item.
The following is an example code, where we will check if an element is present in the tuple or not.
tuple=('Tutorialspoint', 'is', 'the', 'best', 'platform', 'to', 'learn', 'new', 'skills') print("Tutorialspoint" in tuple) print("HelloWorld" in 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
Following is another example showing the usage of the 'in' operator in a tuple -
my_tuple = (5, 1, 8, 3, 7) print(8 in my_tuple) print(0 in my_tuple)
After running the program, you will get this result -
True False
Example 3
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)
This output will be displayed when the program runs -
True False
Example 4
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)
This will lead to the following outcome -
True False
Example 5
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)
The result of this Python program is as follows -
True False