Python Tutorial Python Advanced Python References Python Libraries

Python not in Keyword



The Python not in keyword is a membership operator which validates no membership of the element in the sequence like list, tuple, set, dictionary etc. It returns true when the element is not present in the sequence, otherwise it returns false.

Syntax

(element not in sequence)          

Example:

In the example below, not in keyword is used to check no membership of variable x in the given list called days.

days = ['MON','TUE','WED','THU','FRI']
x = 'SUN'
if x not in days:
  print('yes,', x ,'is not present in the list.')
else:
  print('No,', x ,'is present in the list.')

The output of the above code will be:

yes, SUN is not present in the list.

Example:

In the example below, not in keyword is used to find out all elements of list list1 which are not present in list list2.

list1 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
list2 = [20, 40, 60,  80, 100]
print('These numbers are present only in list1.')
for x in list1:
  if x not in list2:
    print(x)

The output of the above code will be:

These numbers are present only in list1.
10
30
50
70
90

❮ Python Keywords

5