Python: Check if Array/List Contains Element/Value

# Python: Check if Array/List Contains Element/Value

### Introduction

In this tutorial, we'll take a look at how to check if a list contains an element or value in Python. We'll use a list of strings, containing a few animals:

animals = ['Dog', 'Cat', 'Bird', 'Fish']


### Check if List Contains Element With for Loop

A simple and rudimentary method to check if a list contains an element is looping through it, and checking if the item we're on matches the one we're looking for. Let's use a for loop for this:

for animal in animals:
if animal == 'Bird':
print('Chirp!')


This code will result in:

Chirp!


### Check if List Contains Element With in Operator

Now, a more succint approach would be to use the built-in in operator, but with the if statement instead of the for statement. When paired with if, it returns True if an element exists in a sequence or not. The syntax of the in operator looks like this:

element in list


Making use of this operator, we can shorten our previous code into a single statement:

if 'Bird' in animals: print('Chirp')


This code fragment will output the following:

Chirp


This approach has the same efficiency as the for loop, since the in operator, used like this, calls the list.__contains__ function, which inherently loops through the list - though, it's much more readable.

### Check if List Contains Element With not in Operator

By contrast, we can use the not in operator, which is the logical opposite of the in operator. It returns True if the element is not present in a sequence.

Let's rewrite the previous code example to utilize the not in operator:

if 'Bird' not in animals: print('Chirp')


Running this code won't produce anything, since the Bird is present in our list.

But if we try it out with a Wolf:

if 'Wolf' not in animals: print('Howl')


This code results in:

Howl


### Check if List Contains Element With Lambda

Another way you can check if an element is present is to filter out everything other than that element, just like sifting through sand and checking if there are any shells left in the end. The built-in filter() method accepts a lambda function and a list as its arguments. We can use a lambda function here to check for our 'Bird' string in the animals list.

Then, we wrap the results in a list() since the filter() method returns a filter object, not the results. If we pack the filter object in a list, it'll contain the elements left after filtering:

retrieved_elements = list(filter(lambda x: 'Bird' in x, animals))
print(retrieved_elements)


This code results in:

## Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

['Bird']


Now, this approach isn't the most efficient. It's fairly slower than the previous three approaches we've used. The filter() method itself is equivalent to the generator function:

(item for item in iterable if function(item))


The slowed down performance of this code, amongst other things, comes from the fact that we're converting the results into a list in the end, as well as executing a function on the item on each iteration.

### Check if List Contains Element Using any()

Another great built-in approach is to use the any() function, which is just a helper function that checks if there are any (at least 1) instances of an element in a list. It returns True or False based on the presence or lack thereof of an element:

if any(element in 'Bird' for element in animals):
print('Chirp')


Since this results in True, our print() statement is called:

Chirp


This approach is also an efficient way to check for the presence of an element. It's as efficient as the first three.

### Check if List Contains Element Using count()

Finally, we can use the count() function to check if an element is present or not:

list.count(element)


This function returns the occurrence of the given element in a sequence. If it's greater than 0, we can be assured a given item is in the list.

Let's check the results of the count() function:

if animals.count('Bird') > 0:
print("Chirp")


The count() function inherently loops the list to check for the number of occurences, and this code results in:

Chirp


### Conclusion

In this tutorial, we've gone over several ways to check if an element is present in a list or not. We've used the for loop, in and not in operators, as well as the filter(), any() and count() methods.

Last Updated: March 19th, 2021

Get tutorials, guides, and dev jobs in your inbox.

Project

### Real-Time Road Sign Detection with YOLOv5

# python# machine learning# computer vision# pytorch

If you drive - there's a chance you enjoy cruising down the road. A responsible driver pays attention to the road signs, and adjusts their...

David Landup
Details
Project

### Data Visualization in Python: The Collatz Conjecture

# python# matplotlib# data visualization

The Collatz Conjecture is a notorious conjecture in mathematics. A conjecture is a conclusion based on existing evidence - however, a conjecture cannot be proven....

Details