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.
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’ .
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’ .
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:
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 returns True because the integer 42 exists in the set .
>>> 42 in True >>> 'finxter' in 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 returns True because the string key exists in the dictionary.
>>> 'a' in True >>> 'c' in False >>> 42 in 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.
>>> 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) |
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!
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.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.
Be on the Right Side of Change 🚀
- The world is changing exponentially. Disruptive technologies such as AI, crypto, and automation eliminate entire industries. 🤖
- Do you feel uncertain and afraid of being replaced by machines, leaving you without money, purpose, or value? Fear not! There a way to not merely survive but thrive in this new world!
- Finxter is here to help you stay ahead of the curve, so you can keep winning as paradigms shift.
Learning Resources 🧑💻
⭐ Boost your skills. Join our free email academy with daily emails teaching exponential with 1000+ tutorials on AI, data science, Python, freelancing, and Blockchain development!
Join the Finxter Academy and unlock access to premium courses 👑 to certify your skills in exponential technologies and programming.
New Finxter Tutorials:
Finxter Categories: