The Most Pythonic Way to Check If a List Contains an Element

5/5 - (2 votes)

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.

The Most Pythonic Way to Check If a List Contains an Element

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.)

List Membership with Keyword 'in'
lst = [1, 'Alice', 3]
if 'Alice' in lst:

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:

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 True.

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 'war'.

Method 2: Set Conversion + in

The 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:

if 'Bob' in s:

if 'Bob' not in s:
    print('not Bob')

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':
# 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]
# ['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.

Related article:

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!

The 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):
# 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 'A'.

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!

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.

Join the free webinar now!