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.
Checking membership is exemplified in the following code snippet (see Figure 1):
>>> item = 42 >>> my_list = list(range(1, 43)) >>> item in my_list True
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.
Operator | Meaning | Example |
---|---|---|
in | True if value/variable is found in the sequence | x in my_list |
not in | True if value/variable is not found in the sequence | x 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' True
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' True
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] True >>> 'finxter' in ['finxter', 'learn', 'python'] True
However, you cannot check if a sublist exists in a larger list like so:
>>> [1, 2] in [1, 2, 3] False
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} True >>> 'finxter' in {'finxter', 'learn', 'python'} True
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} True >>> 'c' in {'a': 1, 'b': 2} False >>> 42 in {42: [1, 2], 22: [3, 4]} True
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] True
- 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 Type | Runtime Complexity |
---|---|
list | O(n) |
set | O(1) |
dict | O(1) |
tuple | O(n) |
string | O(n) |
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!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. 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?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
๐ If your answer is YES!, consider becoming 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.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar โHow to Build Your High-Income Skill Pythonโ and learn how I grew my coding business online and how you can, tooโfrom the comfort of your own home.