Open In App

Python - Check if one list is subset of other

Last Updated : 18 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Checking if one list is a subset of another is a common task when working with data collection. In this article, we will see different ways to perform this check.

Using set.issubset() Method

issubset() method is the best way to check if all elements of one list exist in another. It Converts lists to sets, eliminating duplicate elements which improves efficiency for large lists.

Python
a = [1, 2, 3]
b = [1, 2, 3, 4, 5]

# Check if a is a subset of b
is_subset = set(a).issubset(b)
print(is_subset)  

Output
True

Explanation:

  • set(a) converts list a into a set.
  • issubset(b) checks if all elements of a exist in b.
  • Returns True if a is a subset of b.

Let's explore some more methods to check if one list is a subset of other.

Using all() with List Comprehension

We can use the all() function with list comprehension to verify if every element in one list exists in the other .

Python
a = [1, 2, 3]
b = [1, 2, 3, 4, 5]

# Check if a is a subset of b
is_subset = all(x in b for x in a)
print(is_subset) 

Output
True

Explanation:

  • all() checks if the condition x in b is True for all elements x in a.
  • Returns True if all elements of a are in b.

Using set.intersection()

By comparing the intersection of two sets using set.intersection(), we can determine if one list is a subset of another.

Python
a = [1, 2, 3]
b = [1, 2, 3, 4, 5]

# Check if a is a subset of b
is_subset = set(a) & set(b) == set(a)
print(is_subset) 

Output
True

Explanation:

  • set(a) & set(b) computes the common elements between a and b.
  • Comparing it with set(a) confirms if a is entirely included in b.

Using Loops

For a more manual method, we can iterate through the first list and check each element against the second list.

Python
a = [1, 2, 3]
b = [1, 2, 3, 4, 5]

# Check if a is a subset of b
is_subset = True
for x in a:
    if x not in b:
        is_subset = False
        break

print(is_subset)

Output
True

Explanation:

  • A for loop iterates through each element in a.
  • If any element is not found in b, the check fails, and the loop breaks.

Next Article
Practice Tags :

Similar Reads