'How to print all the unique combinations of a list?
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
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mozway |