Computer >> Computer tutorials >  >> Programming >> Python

How does in operator work on list in Python?


Python's in operator lets you loop through all the members of a collection(such as a list or a tuple) and check if there's a member in the list that's equal to the given item. 

example

my_list = [5, 1, 8, 3, 7]
print(8 in my_list)
print(0 in my_list)

Output

This will give the output −

True
False

Note that in operator against dictionary checks for the presence of key. 

example

my_dict = {'name': 'TutorialsPoint', 'time': '15 years', 'location': 'India'}
print('name' in my_dict)

Output

This will give the output −

True

It can also be used to check the presence of a sequence or substring against string. 

example

my_str = "This is a sample string"
print("sample" in string)

Output

This will give the output −

True

in can be used in many other places and how it works in those scenarios varies a lot. This is how in works in lists. It starts comparing references of objects from the first one till it either finds that object in the list or reaches the end of the list.