The standard way of checking if an element exists in a list is to use the
in keyword. For example,
'Alice' in [1, 'Alice', 3] will return
True while the same returns False for
'Bob'. If you need to check more complicated conditions, use the
any(condition(x) for x in list) function with a generator expression.
In this article, you’ll not only learn the most Pythonic way to check membership for an element in a Python list. It will also make you a better coder—teaching some key concepts in practice like generator expressions and runtime complexity. So keep reading!
Problem: How to check if a given list contains a given element?
Example: You want a Boolean expression to replace the placeholder function
lst.contains(x) in the following code.
lst = [1, 'Alice', 3] if lst.contains(x): # Do something
Have a look at the following methods that accomplish this—some are better than others!
Exercise: Run the code. Figure out for each method in which case you’d use it!
Method 1: Membership with Keyword ‘in’
The standard way of checking if an element exists in a list is to use the
in keyword. (For more keywords, download my Python keywords cheat sheet.)
lst = [1, 'Alice', 3] if 'Alice' in lst: print('yes')
The output is
'yes' because the string element
'Alice' exists in the list.
If you try the same with the string
'Bob', there won’t be any output:
if 'Bob' in lst: print('Bob')
Python prints nothing to the shell. To make this work, you can use the complementary
not in operator:
if 'Bob' not in lst: print('not Bob')
The output will be
'not Bob' because the expression
'Bob' not in lst evaluates to
Python internally runs the
__contains__ method of a given class to check membership with the in keyword. You can customize it for your own objects by overwriting the method. Here’s a dummy example that points out an extremely useful Python trick:
class Everything: def __contains__(self, *elem, **k): return True universe = Everything() print('Bob' in universe) # True print('Alice' in universe) # True print(42 not in universe) # False
You can try this yourself in your interactive code shell:
Exercise: Change the universe so that it doesn’t contain the word
Method 2: Set Conversion + in
in keyword on lists leads to linear runtime complexity. In other words, you need to perform up to
n operations to check if an element exists in a list with
n elements. If the list has thousands of elements, this can significantly hurt the runtime complexity of your algorithm—if you need to perform a lot of checks.
In this case, it’s far better to convert a list to a set and check membership in a set which has constant runtime complexity—no matter how large the set is, it only costs a constant number of operations to check if an element is in it.
Here’s the code:
lst = [1, 'Alice', 3] s = set(lst) if 'Alice' in s: print('yes') if 'Bob' in s: print('Bob') if 'Bob' not in s: print('not Bob') ''' yes not Bob '''
The output is exactly the same as in the previous examples in Method 1: the code is semantically equivalent. The only difference is that you create a set once (linear runtime complexity) and check membership on the set (constant runtime complexity for each check). Overall, this makes your code up to three times more efficient.
Exercise: Think why this makes your code up to three times more efficient!
Method 3: Naive for Loop
There’s always a naive way of doing things. Sometimes, the naive approach is also the best one. But, in our case, it’s the worst!
Here’s the naive approach of using a for loop to check if an element is in a list:
lst = [1, 'Alice', 3] for x in lst: if x == 'Alice': print('yes') # yes
The code is not concise and not readable. Plus, if the element exists multiple times in the list, the conditional code will be executed multiple times. However, if this is what you want to accomplish, it’s an absolutely viable path to go—and I’d consider it the most Pythonic way to execute a complicated condition for multiple matches in a list.
If the condition is simple, you can also use list comprehension to improve the code and make it more concise.
Method 5: List Comprehension and Conditional Search
Let’s have a look how you can use list comprehension to perform a simple operation for each matching element (rather than just returning
True if the element exists at least once in the list).
In the following code, you replace all occurrences of the string
'Alice' with the new string
'x' for encryption. An application would be the new privacy laws in Europe that require you to anonymize the use of certain names on your web page.
lst = ['Alice', 'Alice', 'Bob', 42, 'Alice'] encrypt_alice = ['x' if x=='Alice' else x for x in lst] print(encrypt_alice) # ['x', 'x', 'Bob', 42, 'x']
The list comprehension statement
['x' if x=='Alice' else x for x in lst] applies the ternary expression
'x' if x=='Alice' else x to each element
x in the original list—and creates a new list with the results. You can use arbitrary expressions to modify each list element or filter out certain elements from the list.
Method 4: any()
This fourth way of checking membership is quite Pythonic and it’s used in some practical code bases. In any case, it’s good if you know the
any() method in Python!
any(iterable) method returns
True if at least one element in the
iterable evaluates to
True. You can think of it as the logical OR operation. In combination with a generator expression to dynamically create an iterable of Booleans (to check if a certain condition applies to each element in the list), this is a powerful tool in your tool belt.
lst = [1, 'Alice', 3] if any(x=='Alice' for x in lst): print('yes') # yes
The advantage of this method is that it allows you to check arbitrary complicated conditions, rather than just check membership. For example, you could use regular expressions to match all strings in your list that start with the character
To learn about regular expressions (the text-processing superpower that’ll help you be more productive in text processing tasks such as building your own search engine), check out my brand-new interactive book ‘The Smartest Way to Learn Python Regex’ (link to book sales page)!
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.
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. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, 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.