Check if all values in a list are in another list in Python

avatar

Borislav Hadzhiev

Last updated: Aug 12, 2022

banner

Photo from Unsplash

Check if all values in a list are in another list in Python #

To check if all values in a list are in another list:

  1. Use the set() class to convert the list to a set.
  2. Use the issubset() method to check if all values in the list are in the other list.
  3. The issubset() method will return True if all values in the list are in the other list.
main.py
list_1 = ['one', 'two', 'three'] list_2 = ['one', 'two', 'three', 'four'] if set(list_1).issubset(list_2): # 👇️ this runs print('All values in the list are in the other list') else: print('Not all of the values in the list are in the other list') # 👇️ True print(set(list_1).issubset(list_2))

We used the set() class to convert the list to a set object.

We converted the list to a set, so we can use the issubset method.

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

main.py
list_1 = ['one', 'two', 'three'] list_2 = ['one', 'two', 'three', 'four'] print(set(list_1).issubset(list_2)) # 👉️ True print(set(list_2).issubset(list_1)) # 👉️ False

In other words, set(list_1).issubset(list_2) checks if every element of list_1 is in list_2.

Alternatively, you can use the all() function.

Use the all() function to check if all values in a list are in another list, e.g. if all(item in list_2 for item in list_1):. The all() function will return True if all of the values in the list are in the other list.

main.py
list_1 = ['one', 'two', 'three'] list_2 = ['one', 'two', 'three', 'four'] if all(item in list_2 for item in list_1): print('All values in the list are in the other list') else: print('Not all of the values in the list are in the other list')

We used a generator expression to iterate over the list.

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 value is present in the other 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).

main.py
list_1 = ['one', 'two', 'three'] list_2 = ['one', 'two', 'three', 'four'] # 👇️ True print(all(item in list_2 for item in list_1))

If the all() function finds a value that is not in the other list, it will short-circuit returning False.

main.py
list_1 = ['hello', 'two', 'three'] list_2 = ['one', 'two', 'three', 'four'] # 👇️ False print(all(item in list_2 for item in list_1))
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.