Categories
Python Answers

How to get all subsets of a set with Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *