Check if multiple values are in a list in Python

avatar

Borislav Hadzhiev

Last updated: Jul 15, 2022

banner

Photo from Unsplash

Check if multiple values are in a list in Python #

Use the all() function to check if multiple values are in a list, e.g. if all(value in my_list for value in multiple_values):. The all() function will return True if all of the specified values are in the list and False otherwise.

main.py
my_list = ['one', 'two', 'three', 'four', 'five'] multiple_values = ['one', 'two', 'three'] if all(value in my_list for value in multiple_values): # 👇️ this runs print('All of the values are in the list') else: print('Not all of the values are in the list') # 👇️ True print(all(value in my_list for value in multiple_values))

We used a generator expression to iterate over the collection of multiple values.

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

On each iteration, we check if the current value is present in the list and return the result.

The all() built-in function takes an iterable as an argument and returns True if all elements in the iterable are truthy (or the iterable is empty).

If one of the values isn't present in the list, the all() function will short-circuit returning False.

main.py
my_list = ['one', 'two', 'three', 'four', 'five'] multiple_values = ['fifty', 'two', 'three'] if all(value in my_list for value in multiple_values): print('All of the values are in the list') else: # 👇️ this runs print('Not all of the values are in the list') # 👇️ False print(all(value in my_list for value in multiple_values))

Alternatively, you can use the set() class to convert the collection of values to a set object to be able to use the issubset() method.

main.py
my_list = ['one', 'two', 'three', 'four', 'five'] multiple_values = ['one', 'two', 'three'] if set(multiple_values).issubset(my_list): # 👇️ this runs print('All of the values are in the list') else: print('Not all of the values are in the list') # 👇️ True print(set(multiple_values).issubset(my_list))

The set.issubset method tests if every element of the set is in the provided sequence.

The condition evaluates to True only if all of the specified values are present in the list.

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.