How to Check if One List is a Subset of Another List in Python?

Estimated read time 1 min read

To check if one list is a subset of another list in Python, you can use the issubset() method or the set intersection operator &.

Here’s an example using issubset():

list1 = [1, 2, 3, 4, 5]
list2 = [1, 2, 3]

if set(list2).issubset(set(list1)):
    print("list2 is a subset of list1")
else:
    print("list2 is not a subset of list1")

In this example, set(list2).issubset(set(list1)) checks if all elements in list2 are present in list1. If list2 is a subset of list1, the code prints “list2 is a subset of list1”.

Alternatively, you can use the set intersection operator & to find the common elements between the two sets:

list1 = [1, 2, 3, 4, 5]
list2 = [1, 2, 3]

if set(list2) & set(list1) == set(list2):
    print("list2 is a subset of list1")
else:
    print("list2 is not a subset of list1")

In this example, set(list2) & set(list1) finds the intersection of the two sets, and set(list2) is compared to the intersection to check if all elements in list2 are present in list1. If list2 is a subset of list1, the code prints “list2 is a subset of list1”.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply