Python in Keyword

Python in Keyword

Python in keyword can be used as

  • Membership Operator, to check if a value is present in the given collection, or
  • iterate over a collection in For Loop

in-keyword as Membership Operator

In this case, in keyword takes two operands. Left operand is the value, and the right operand is the collection.

The syntax of the expression is

x in collection

where x is a value, and collection is any collection of items like a list, tuple, set, string, etc.

If the element or value x is present in the collection, then the above expression returns a boolean value of True, or else the expression returns False.

Example

In this example, we take a list of strings, and check if the value "mango" is present in this list, using in keyword.

Python Program

fruits = ['apple', 'banana', 'cherry', 'mango']
x = 'mango'
if x in fruits:
    print('x is in the given list.')
else:
    print('x is not in the given list.')
Run

Output

x is in the given list.

in-keyword to Iterate over a Collection

In this case, in keyword is used to iterate over a given collection in For Loop, and access the next item during each iteration.

The syntax of the expression is

for x in collection:
    #code

where x is the next value during respective iteration, and collection is any collection of items like a list, tuple, set, string, etc.

Example

In this example, we take a list of strings, and iterate over the items in this list, using in keyword.

Python Program

fruits = ['apple', 'banana', 'cherry', 'mango']
for x in fruits:
    print(x)
Run

Output

apple
banana
cherry
mango

Summary

In this tutorial of Python Examples, we learned about Python-in keyword, and how to use it in scenarios like decision making, and iteration.