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