Operators

Membership Operators

Explore how to apply Python membership operators to determine if elements exist within sequences like lists, strings, and sets. Understand the behavior of in and not in operators, including case sensitivity in strings, to write effective and accurate membership tests.

Membership operators

Name Symbol Syntax Explanation
In operator in val in my_list Returns True if the element is present in the iterable
Not in operator not in val not in my_tuple Returns True if the element is not present in the iterable

For demonstration purposes, let’s consider a list of numbers, numbers_list = [1,3,5,7,9], and a specific element, 5, which we’ll call target_element. Applying the membership operators would give the following results:

The in operator

Checking if 5 is present in the list gives True.

Expression: 5 in numbers_list

The not in operator

Checking if 5 is not present in the list gives False.

Expression: 10 not in numbers_list

Code

We can put this effectively into Python code, and you can even change the list and target element to experiment with the code yourself! Click on the “Run” button to see the output.

numbers_list = [1, 3, 5, 7, 9] target_element = 5 is_present = target_element in numbers_list print(is_present) is_not_present = target_element not in numbers_list print(is_not_present)

Membership operators in Python

Note: Membership operators are usually paired with sequences like lists, tuples, strings, and sets (any iterable data type).

Let’s take a look at another piece of code—this time using strings. The following code will result in False, as Python is case sensitive and p is not considered the same as P.

word = "Python" print('p' in word)

Membership operators in Python

On this page

    In This Module