create a list of all the subsets of a given list in python 3.x

Question:

how can I create a list of all the subsets of a given list in python 3.x?
the list given be like [1,2,3] and i want an output like

[[1],[2],[3],[1,2],[2,3],[1,3],[1,2,3],[]]
Asked By: RISHABH BANSAL

||

Answers:

You can use itertools.combinations to get the combinations:

>>> import itertools
>>> xs = [1, 2, 3]

>>> itertools.combinations(xs, 2)  # returns an iterator
<itertools.combinations object at 0x7f88f838ff48>
>>> list(itertools.combinations(xs, 2))  # yields 2-length subsequences
[(1, 2), (1, 3), (2, 3)]


>>> for i in range(0, len(xs) + 1):  # to get all lengths: 0 to 3
...     for subset in itertools.combinations(xs, i):
...         print(list(subset))
... 
[]
[1]
[2]
[3]
[1, 2]
[1, 3]
[2, 3]
[1, 2, 3]

combining with list comprehension, you will get what you want:

>>> [list(subset) for i in range(0, len(xs) + 1)
                  for subset in itertools.combinations(xs, i)]
[[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
Answered By: falsetru

I tried this. without recursion. which worked out successfully.

A is list , K is length of every subset

    def subsets(A,K):
       sets = []
       for j in range(len(A)-K+1):
           mySet = []
           for i in range(j,K+j):  
               mySet.append(A[i])
           sets.append(mySet)
    return sets

The question is really to ask the powerset. Here is another way to generate it:
(without the itertools.combinations())

>>> L = [1, 2, 3]
>>> res = [[]]
>>> for e in L:
    res += [sub + [e] for sub in res]

>>> res
[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

Or you can just use this 3rd party lib more_itertools: powerset (as the name aptly reflects its purpose).

>>> import more_itertools

>>> list(more_itertools.powerset(L))
[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
>>> 
Answered By: Daniel Hao

You don’t need to install more_intertools if you’re going to use only one function from there. You can check Itertools Recipes from the itertools documentation. It has such recipe:

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))

Actually, more_itertools.powerset has exactly the same implemention.

Answered By: funnydman
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.