Check if one of multiple values is in a list in Python

avatar

Borislav Hadzhiev

Last updated: Aug 10, 2022

banner

Photo from Unsplash

Check if one of multiple values is in a list in Python #

Use the any() function to check if one of multiple values is in a list, e.g. if any(item in my_list for item in multiple_values):. The any() function will return True if at least one of the values is in the list and False otherwise.

main.py
my_list = ['one', 'two', 'three'] multiple_values = ['four', 'five', 'three'] # ✅ check if one of multiple values is in a list if any(item in my_list for item in multiple_values): # 👇️ this runs print('At least one of the values is in the list') else: print('None of the values are in the list') # ------------------------------------------------- # ✅ check if one of multiple values is in a list and get the value if any((match := item) in my_list for item in multiple_values): # 👇️ this runs print('At least one of the values is in the list') print(match) # 👉️ 'three' else: print('None of the values are in the list')

We used a generator expression to iterate over a list.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

In the example, we iterate over the multiple values collection and check if each value is contained in the list.

The any function takes an iterable as an argument and returns True if any element in the iterable is truthy.

The any() function will short-circuit returning True if at least one value is contained in the list.

You can use the assignment expression syntax if you need to get the value that is contained in the list.

main.py
my_list = ['one', 'two', 'three'] multiple_values = ['four', 'five', 'three'] if any((match := item) in my_list for item in multiple_values): # 👇️ this runs print('At least one of the values is in the list') print(match) # 👉️ 'three' else: print('None of the values are in the list')
Assignment expressions allow us to assign to variables within an expression using the NAME := expression syntax.

If the condition is met at least once, the any() function returns True.

If the iterable we pass to the any() function is empty or none of the elements in the iterable are truthy, the any function returns False.

main.py
my_list = ['one', 'two', 'three'] multiple_values = ['four', 'five', 'six'] if any((match := item) in my_list for item in multiple_values): print('At least one of the values is in the list') print(match) else: # 👇️ this runs print('None of the values are in the list')

None of the multiple values is contained in the list, so the condition is never met and any() returns False.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.