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