How does the in operator work in a Python list?

Python Methods and Functions

The Python in statement allows you to loop through all the elements of a collection (such as a list or a tuple) and check if the list has an element equal to the given element.




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 the key is checked against the dictionary .


< p>




Example 2

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



Output 2

This will give the output &



 True 

It can also be used to check for a sequence or substring in a string.




Example 3

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



Output 3

This will give output &

 True 

It can be used in many other places, and the way it works in these scenarios is very different. gets angry. This is how it works in lists. It starts comparing object references from the first until it finds that object in the list or reaches the end of the list.







Get Solution for free from DataCamp guru