Membership Operators#

We previously discussed the membership operator; however, now that we’ve introduced collections – variables that can store more than one value – we want to revisit the membership operators in and not in.

The membership operator: in#

Python uses in and not in to compare membership. These operators return booleans.

Membership operators are used to check whether a value or variable is found in a collection.

  • in : True if value is found in the sequence

  • not in : True if value is not found in the sequence

Membership in lists and tuples#

In lists and tuples, in checks if the value is an element in the list.

lst_again = [True, 13, None, 'apples']
'apple' in lst_again
False

in works at the element-level in collections, so the string ‘apple’ is NOT a memeber of lst_again because it is not an element in the list…even though it is part of an element in the list.

'apple' in lst_again
False

not in returns True when the value is not in the list:

13 not in lst_again
False

Membership in dictionaries#

In a dictionary, checks if value is a key in the dictionary. So, 'Ezra' is a member of dict_again, as it is a key; however, 9 is not, as that is a value in dict_again.

dict_again = {'Kayden': 2, 'Ezra': 9}
'Ezra' in dict_again
True

It does NOT check for values:

9 in dict_again
False

Membership in strings#

Recall that for strings, in checks if a sequence of characters is found in the string.

my_string = 'I love COGS 18!'
'love' in my_string
True

The order of the sequence being checked matters:

'evol' in my_string
False