Check subset in list Python

Summary: in this tutorial, youll learn about how to use the Python issubset[] method to check if a set is a subset of another set.

Introduction to the Python issubset[] method

Suppose that you have two sets A and B. The set A is a subset of the set B if all elements of A are also elements of B. Then, the set B is a superset of the set A.

The following Venn diagram illustrates that the set A is a subset of the set B:

The set A and set B can be equal. If the set A and set B are not equal, A is a proper subset of B.

In Python, you can use the Set issubset[] method to check if a set is a subset of another:

set_a.issubset[set_b]
Code language: CSS [css]

If the set_a is a subset of the set_b, the issubset[] method returns True. Otherwise, it returns False.

The following example uses the issubset[] method to check if the set_a is a subset of the set_b:

numbers = {1, 2, 3, 4, 5} scores = {1, 2, 3} print[scores.issubset[numbers]]
Code language: PHP [php]

Output:

True
Code language: PHP [php]

By definition, a set is also a subset of itself. The following example returns True:

numbers = {1, 2, 3, 4, 5} print[numbers.issubset[numbers]]
Code language: PHP [php]

Output:

True
Code language: PHP [php]

The following example returns True because some elements in the numbers set arent in the scores set. In other words, the numbers set is not a subset of the scores set:

numbers = {1, 2, 3, 4, 5} scores = {1, 2, 3} print[numbers.issubset[scores]]
Code language: PHP [php]

Output:

False
Code language: PHP [php]

Using subset operators

Besides using the issubset[] method, you can use subset operators [

Chủ Đề