8

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],[]]
falsetru
  • 357,413
  • 63
  • 732
  • 636

4 Answers4

9

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]]
falsetru
  • 357,413
  • 63
  • 732
  • 636
8

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)]
>>> 
Daniel Hao
  • 4,922
  • 3
  • 10
  • 23
1

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.

funnydman
  • 9,083
  • 4
  • 40
  • 55
0

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
  • This is equivalent to `def subsets(A, K): return [A[j:K+j] for j in range(len(A)-K+1)]` but it doesn't return all the subsets of length `K`, only the contiguous ones. For instance, `subsets([1,2,3], 2)` returns `[[1,2], [2,3]]` and misses `[1,3]`. – Stef Feb 26 '23 at 00:18