Python Membership “in” Operator

Python’s “in” operator is a reserved keyword to test membership of the left operand in the collection defined as the right operand. For example, the expression x in my_list checks if object x exists in the my_list collection, so that at least one element y exists in my_list for that x == y holds. You can check membership using the “in” operator in collections such as lists, sets, strings, and tuples.

Figure 1: Check membership of item 42 in the list of integers.

Checking membership is exemplified in the following code snippet (see Figure 1):

>>> item = 42
>>> my_list = list(range(1, 43))
>>> item in my_list

Here’s another example on strings:

x = 'alice'
my_list = ['alice', 'bob', 'carl']
print(x in my_list)
# True

In fact, Python has two membership operators in and not in that test whether a value exists in a collection such as string, list, tuple, set, and dictionary.

inTrue if value/variable is found in the sequencex in my_list
not inTrue if value/variable is not found in the sequencex not in my_list

Video Membership

Python “in” Operator String

You can check membership of a character in a string using the “in” keyword operator. For example, the expression 'f' in 'finxter' returns True because the character 'f' exists in the string 'finxter'.

>>> 'f' in 'finxter'

You can also check membership of a string in another string using the “in” operator. For example, the expression 'inx' in 'finxter' returns True because the string 'inx' exists in the string 'finxter'.

>>> 'inx' in 'finxter'

Python “in” Operator List

You can check membership of an individual object in a list using the “in” keyword operator. For example, the expression 42 in [1, 2, 42] returns True because the integer 42 exists in the list [1, 2, 42].

>>> 42 in [1, 2, 42]
>>> 'finxter' in ['finxter', 'learn', 'python']

However, you cannot check if a sublist exists in a larger list like so:

>>> [1, 2] in [1, 2, 3]

The reason is that the sublist is an object itself and membership only checks if this particular object is in the list. For example, you may want to check if a list is a member of the list of lists.

Python “in” Operator Set

You can check membership of an individual object in a set with the “in” keyword operator. For example, the expression 42 in {1, 2, 42} returns True because the integer 42 exists in the set {1, 2, 42}.

>>> 42 in {1, 2, 42}
>>> 'finxter' in {'finxter', 'learn', 'python'}

Python “in” Operator Dictionary

You can check membership of an individual key in a dictionary with the “in” keyword operator. For example, the expression 'a' in {'a': 1, 'b': 2} returns True because the string key exists in the dictionary.

>>> 'a' in {'a': 1, 'b': 2}
>>> 'c' in {'a': 1, 'b': 2}
>>> 42 in {42: [1, 2], 22: [3, 4]}

Python “in” Operator Case Insensitive

A case-insensitive check if a given string is in a list of strings—ignoring whether the strings are uppercase or lowercase—can be done by converting all strings to a canonical lowercase (or uppercase) representation using string.lower() or string.upper() methods, for example, in a list comprehension statement.

Here’s how this works:

>>> user = 'ALICE'
>>> usernames = ['alice', 'bob', 'CARL']
>>> user.lower() in [x.lower() for x in usernames]
  • Convert the string 'ALICE' to the lowercase version 'alice'.
  • Convert the string list ['alice', 'bob', 'CARL'] to the lowercase versions ['alice', 'bob', 'carl'].

Python “in” Operator Overloading

Operator overloading replaces the standard meaning of an operator with a customized version. You can overload the “in” operator by overriding the __contains__(self, item) method and return a Boolean value True or False whether the item exists in the custom class object or not.

Here’s a generalized example:

class MyClass:
    def __init__(self, my_collection):
        self.my_collection = my_collection

    def __contains__(self, item):
        return item in self.my_collection

my = MyClass('hello world')
print('hello' in my)
# True

The custom class MyClass wouldn’t generally support membership. But by defining the __contains__() “dunder” method, you can reduce membership of an object in the class to the problem of checking membership of an object in a collection using the “in” operator. Now, you can check, for example, if a string is a member of a custom class object.

Python “in” Operator Runtime Complexity

The following table shows the runtime complexities of the “in” operator for different basic collection data structures with n elements.

Collection TypeRuntime Complexity
Table: Runtime complexity of checking membership for lists, sets, dicts, tuples, and strings with n elements.

Checking membership for lists, tuples, and strings has linear runtime complexity. Python iterates over the whole collection and compares the searched element against every single collection element. For large collections, checking membership can become prohibitively expensive.

Checking membership for sets and dictionaries has constant runtime complexity. Python uses a hash table to instantly check if an element is in the set or dict—no matter how large the data structure. Especially for large collections such as n=10000 elements, sets should generally be preferred over lists and tuples.

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!