Python Reference ยท Dictionaries and Sets
Python set.issubset() method
Reference for Python set.issubset(): check whether every element of a set appears in another collection, the <= and < operators, empty sets and equal sets.
The issubset() method returns True if every element of the set is also present in another collection. In other words, the set fits entirely inside the other one.
The method has operator forms: a <= b means "a is a subset of b", and a < b means "a is a proper subset of b" (a subset that is not equal to b).
{1, 2}.issubset({1, 2, 3}) # True
{1, 4}.issubset({1, 2, 3}) # False
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
set.issubset(other) set <= other set < other
| Name | Description |
|---|---|
other |
Any iterable for the method form. Both operands must be sets (or frozensets) for the operators. |
Return value: True if all elements of the set are in other, otherwise False.
Raises: TypeError if other is not iterable, or if an operator is used with a non-set.
Usage notes
- Every set is a subset of itself, and the empty set is a subset of every set. Use
<when you need a proper subset. - The method takes any iterable, and converts it to a set first. That conversion costs time proportional to its length, so pass a set when you can.
- The operators are strict about types.
<= [1, 2]raisesTypeError, while.issubset([1, 2])works. - Duplicates do not matter. A list
[1, 1, 2]is treated like the set{1, 2}. - Direction matters.
a.issubset(b)is the same asb.issuperset(a). - Works with frozensets in the same way, and a set can be compared to a frozenset.
- A subset check is not an equality check. If you want both directions, compare with
==.
Related
set.issuperset(),set.isdisjoint(),set.difference()- Lesson: Sets