Check if an Element is in a list in Python

Lists are one of the most common data types in Python and are used to store data sequentially. Even if you can add several times the same value, there are cases where you do not want to do that and need to check if an element exists in a list. In this tutorial, I’ll explain some of the approaches you can use to do so.

Use the “in” operator to check if an element is in a list

The simplest way to perform this action is to use the in operator. It will either return True or False depending on whether the element exists in your list or if it doesn’t. For example:

words = ['apple','banana','orange'] result = 'apple' in words print(result)
Code language: Python (python)

Output:

True
Code language: PHP (php)

This operator is often used with an if statement, to perform different actions based on the result.

words = ['apple','banana','orange'] if 'apple' in words: print('The word exists in our list!') else: print('The word doesn\'t exist in our list!')
Code language: Python (python)

Output:

The word exists in our list!
Code language: PHP (php)

Use a for loop to check if an element exists in a list

Another technique consists in using a for loop to check if the element is included in our list. The code is not as readable as our first approach, but it does the job as well.

words = ['apple','banana','orange'] #default result result = False #for loop for element in words: if element == 'strawberry': #we modify value only if element is found result = True print(result)
Code language: Python (python)

Output:

False
Code language: PHP (php)

I’d not advise using a for loop to perform this check because it will negatively impact your code readiness. But if for any reason you do not want to use the in operator, the outcome will be the same.

Use the count() method to check if an element exists in a list

The count() method returns the number of times an element appears in the list. It does not behave exactly like the in operator, but we can obviously use it here.

words = ['apple','banana','orange'] if words.count('apple')>0: print('The word exists in our list!') else: print('the word doesn\'t exist in our list!')
Code language: Python (python)

Output:

The word exists in our list!
Code language: PHP (php)

Use any() function to check if an element exists in a list

The any() function is one of the (many) built-in functions available when you use Python. If you look at its definition, you’ll realize that it actually uses the in operator:

def any(iterable): for element in iterable: if element: return True return False
Code language: Python (python)

You can use it with a list comprehension to check if your element is included in your list.

words= ['apple', 'banane', 'orange'] result = any('strawberry' in words for word in words) print(result)
Code language: Python (python)

Output:

False
Code language: Python (python)

I’d advise using it only if you want to check that all elements from a list are included in another. For one element, you’re adding too much complexity in your code.

Use Pandas to check if an element is in a list

Finally, you can use the famous Pandas library and its isin() method.  I recommend doing it like only if you are already working with a DataFrame. Otherwise, you’ll have to load your list into a Pandas Series, apply the change, and export to a list again.

import pandas as pd df1 = {'strings':['a1','b1','c1','d1']} df2 = {'strings':['a1']} df1 = pd.DataFrame(df1, columns=['strings']) df2 = pd.DataFrame(df2, columns=['strings']) result = df2['strings'].isin(df1['strings']) print(result.iloc[0])
Code language: Python (python)

Output:

True
Code language: Python (python)

Leave a Reply

Your email address will not be published. Required fields are marked *