
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
In this article, we discuss about the ?in' operator and how it works on tuples in python. Before moving on, we will discuss about tuples first.
Tuple
Tuples are a data type that belongs to the sequence data type category. They're similar to lists in Python, but they have the property of being immutable. We can't change the elements of a tuple, but we can execute a variety of actions on them such as count, index, type, etc.
Tuples are created in Python by placing a sequence of values separated by a 'comma', with or without the use of parenthesis for data grouping. Tuples can have any number of elements and any type of data (like strings, integers, lists, etc.).
Example
In the below example we will look at how to create a tuple.
tuple = ('Tutorialspoint', 'is', 'the', 'best', 'platform', 'to', 'learn', 'new', 'skills') print(tuple)
Output
The above code produces the following results
('Tutorialspoint', 'is', 'the', 'best', 'platform', 'to', 'learn', 'new', 'skills')
The "in" operator on a tuple
We use the ?in' operator to check if the object is present in the tuple. The ?in' operator returns "True" if a sequence with the specified value is present in the object and "False" if it is not present.
Example
The ?in' operator in Python allows you to loop through 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 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)
Output
In the above example, the string "Tutorialspoint" is present in the tuple so the in operator returns "True". Whereas, the string "HelloWorld" is not present in the tuple so it returns "False".
True False
Example 2
Following is another example demonstrating 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)
Output
This will give the output ?
True False