Sometimes, we want to get all subsets of a set with Python.
In this article, we’ll look at how to get all subsets of a set with Python.
How to get all subsets of a set with Python?
To get all subsets of a set with Python, we can use the chain.from_iterable
method with the combinations
function.
For instance, we write
from itertools import chain, combinations
def powerset(iterable):
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)
+ 1))
to call chain.from_iterable
with all the combinations of set s
that we get from
combinations(s, r) for r in range(len(s)
+ 1)
We convert the iterable
to a list with list
before we call chain.from_iterable
.
Conclusion
To get all subsets of a set with Python, we can use the chain.from_iterable
method with the combinations
function.