Skip to content
Advertisement

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

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],[]]

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement