user1802143
user1802143

Reputation: 15682

python: create iterator through subsets of a set for a loop

I have a sequence of consecutive integers, for example [1, 2, 3]. I'd like to create an iterator that goes through all the subsets of the set. In this case [], [1],...,[1,2,3]. How could I do this?

Upvotes: 10

Views: 8149

Answers (2)

antshar
antshar

Reputation: 119

Here's another simple way of doing that without extra libraries

set = [1,2,3]
subsets = [[]]

for el in set:
    for i in range(len(subsets)):
        subsets += [subsets[i]+[el]]

print(subsets)

The output:

[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

Or even simpler with the help of list comprehension

set = [1,2,3]
subsets = [[]]

for el in set:
    subsets += [s+[el] for s in subsets]

print(subsets)

Upvotes: 2

Nafiul Islam
Nafiul Islam

Reputation: 82470

The itertools documentation contains a recipe for this construction under the name powerset, if that's what you need.

from itertools import chain, combinations

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

Upvotes: 15

Related Questions