Most functions in itertools
produce tuple
s, but the good news is that a tuple is an iterable, and you can use list(..)
with an iterable to convert the iterable to a list.
We can thus for example map
the results of the itertools, like:
from itertools import combinations
a=[10, 1 ,2, 7, 6, 1, 5]
b=[]
for i in range(len(a)):
for s in map(list, combinations(a,i)):
if s not in b:
b.append(s)
print(b)
But nevertheless this is still not a good idea. A membership check of a list, runs in linear time. Since there are an exponential number of combinations, this means that it will start running in O((n!)2) time, with n the number of elements, which is typically very slow.
A faster way to do this, is using a set
concurrently, that stores the elements, and then each time check membership of the tuple (a set
can not contain list
s, since list
s are unhashable), in case the membership fails, we add it to b
as a list:
from itertools import combinations
a=[10, 1 ,2, 7, 6, 1, 5]
b=[]
seen = set()
for i in range(len(a)):
for s in combinations(a,i):
if s not in seen:
seen.add(s)
b.append(list(s))
print(b)