Check with <= Operator
In the previous step, you learned how to use the issubset()
method to check if one set is a subset of another. In this step, you will learn an alternative way to check for subsets using the <=
operator.
The <=
operator can be used to check if one set is a subset of another. It returns True
if the set on the left side is a subset of the set on the right side, and False
otherwise.
Let's revisit the skills example from the previous step:
skills1 = {"Python", "Data Analysis"}
skills2 = {"Python", "Data Analysis", "Machine Learning", "SQL"}
We want to check if skills1
is a subset of skills2
using the <=
operator.
Open the subset_check.py
file in the ~/project
directory using VS Code. Modify the content of the file to the following:
skills1 = {"Python", "Data Analysis"}
skills2 = {"Python", "Data Analysis", "Machine Learning", "SQL"}
is_subset = skills1 <= skills2
print(is_subset)
Save the file.
Now, execute the script using the python
command in the terminal:
python subset_check.py
The output will be:
True
This indicates that skills1
is indeed a subset of skills2
.
Let's consider another scenario where skills1
is not a subset of skills2
:
Modify the subset_check.py
file to the following:
skills1 = {"Python", "Data Analysis", "Cloud Computing"}
skills2 = {"Python", "Data Analysis", "Machine Learning", "SQL"}
is_subset = skills1 <= skills2
print(is_subset)
Save the file and run it again:
python subset_check.py
The output will be:
False
This is because skills1
contains "Cloud Computing", which is not present in skills2
. Therefore, skills1
is not a subset of skills2
.
It's important to note that the <=
operator also returns True
if the two sets are equal. For example:
set1 = {1, 2, 3}
set2 = {1, 2, 3}
is_subset = set1 <= set2
print(is_subset)
The output will be True
because set1
and set2
are equal. If you want to check if set1
is a proper subset of set2
(i.e., set1
is a subset of set2
but not equal to set2
), you can use the <
operator instead.