0
list_a = [1, 2, 3]

I want to print all the unique combinations from the list like this

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

Note: Without using any module

mozway
  • 194,879
  • 13
  • 39
  • 75

1 Answers1

0

You need a variant of the powerset recipe from itertools:

from itertools import combinations, chain
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(1, len(s)+1))

list_a = [1, 2, 3]

out = list(map(list, powerset(list_a)))

output: [[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]

If you don't want to use itertools you can quite easily reimplement combinations and chain using list comprehensions or functions.

mozway
  • 194,879
  • 13
  • 39
  • 75