Skip to content

Python in operator

  • by

Python in the operator is used to check if a value exists in a group of values (string, list, tuple, etc). The in operator returns True if an element is found. It returns False if not.

Python in operator

A simple example code check specified value is inside the sequence.

list1 = [1, 2, 3, 4, 5]
print(5 in list1)  # True

s = "A is A"
print("is" in s)  # True

tuple1 = (11, 22, 33, 44)
print(88 in tuple1)  # False

Output:

Python in operator

Let’s see the in operator in the if..else condition.

s = "Game of Thrones was the good show"
if "Thrones" in s:
    print('It exists')
else:
    print('Does not exist')

Output: It exists

Note: Python not in operator works opposite of in operator.

Lists, Tuples, Strings: You can use the in operator to check if an element exists within a list, tuple, or string.

Dictionaries: When used with dictionaries, the in operator checks if the specified key exists in the dictionary.

Custom Classes: You can also override the __contains__ method in your custom classes to define custom behavior for the in operator.

The in operator is a convenient way to check membership in Python and is frequently used in conditional statements and loops.

Do comment if you have any doubts or suggestions on this Python operator topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading