search

What is the difference between "in" and "not in" in Python?

In Python, the in and not in operators are used to test the membership of an element in a sequence (such as a list, tuple, string, or set). They have the following key differences:

Positive vs. Negative Membership:

  • in: The in operator returns True if the specified element is found in the sequence.
  • not in: The not in operator returns True if the specified element is not found in the sequence.

Usage:

  • in: The in operator is used to check if an element exists in a sequence. It is typically used in conditional statements or as part of expressions to perform actions based on membership.
  • not in: The not in operator is used to check if an element does not exist in a sequence. It is also used in conditional statements or expressions to perform actions based on non-membership.

Here's an example to illustrate the difference between in and not in:

my_list = [1, 2, 3, 4]

print(2 in my_list)  # Output: True
print(5 in my_list)  # Output: False

print(2 not in my_list)  # Output: False
print(5 not in my_list)  # Output: True

In this example, 2 in my_list returns True because 2 is found in the my_list sequence, while 5 in my_list returns False because 5 is not found in the my_list sequence.

Similarly, 2 not in my_list returns False because 2 is present in the my_list sequence, while 5 not in my_list returns True because 5 is not present in the my_list sequence.

The in and not in operators are useful for conditionally checking membership or non-membership in sequences. They can be used with other data types like strings, tuples, sets, and dictionaries as well.

It's worth mentioning that the in and not in operators perform different operations depending on the sequence type. For example, when used with strings, they check for substring membership rather than individual characters.

Related Questions You Might Be Interested