There are a number of ways to check if a list is a subset of another list in Python. The easiest way is to convert the lists to sets and use the issubset() function.

big_list = [1, 2, 3, 4, 5, 6, 7]
small_list = [1, 2, 3]

print(set(small_list).issubset(set(big_list))

#Output:
True

You can also use the set intersection function to check if a list is a subset of another list in Python.

big_list = [1, 2, 3, 4, 5, 6, 7]
small_list = [1, 2, 3]

print(set(small_list).intersection(set(big_list)) == set(small_list))

#Output:
True

Another method is using the Python all() function.

big_list = [1, 2, 3, 4, 5, 6, 7]
small_list = [1, 2, 3]

print(all(x in big_list for x in small_list))

#Output:
True

When working with collections of data. such as lists, in Python, the ability to get certain information about them is very useful.

One piece of information is if a certain list is a subset, or has all elements contained, in another list.

We can easily check if a list is a subset of another list.

Sets in Python have many great functions which allow us to perform standard set operations easily. Converting our lists to sets will allow us to use the set issubset() function to check if a set is a subset of another set.

Below is an example in Python of how to use issubset() to check if a list is a subset of another list.

big_list = [1, 2, 3, 4, 5, 6, 7]
small_list = [1, 2, 3]

print(set(small_list).issubset(set(big_list))

#Output:
True

Checking if a List is a Subset of Another List Using intersection() in Python

Another way to check if a list is a subset of another list is to check if the intersection of the list with the other list is equal to the original list.

We can check this by converting the lists to sets and using the set intersection() function to get the intersection of the two lists.

Below is how to check if a list is a subset of another with the intersection() function in Python.

big_list = [1, 2, 3, 4, 5, 6, 7]
small_list = [1, 2, 3]

print(set(small_list).intersection(set(big_list)) == set(small_list))

#Output:
True

Using all() Function to Check if List Exists in Another List Using Python

There are many useful built-in Python functions which work on lists that allow us to check conditions, filter, etc.

We can use the Python all() function to loop over elements in a list and check certain conditions.

To check if a list is a subset of another list, we can use all() to check if all elements of a list are in another list.

Below is an example of how to use all() to see if all elements of a list are in another list.

big_list = [1, 2, 3, 4, 5, 6, 7]
small_list = [1, 2, 3]

print(all(x in big_list for x in small_list))

#Output:
True

Hopefully this article has been useful for you to learn how to check if a list is a subset of another list using Python.

Categorized in:

Python,

Last Update: February 26, 2024