Reputation:
i have a list with 1's and 0's. I want to know all possible combinations of them and store each combination in a list of lists. Why are they stored as Tuples, and how to change that ?
import itertools
bitcode = [0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1]
# print(len(bitcode))
listoflist = [[]]
combo_all = itertools.combinations_with_replacement(bitcode, 11)
for bitcode in combo_all:
listoflist.append(bitcode)
# print(listoflist)
# print(len(listoflist))
# print(type(listoflist))
print(listoflist[-1])
print(type(listoflist[-1]))
(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
<class 'tuple'>
Upvotes: 0
Views: 89
Reputation: 44926
Why are they stored as Tuples?
Because that's how the itertools
module is implemented. itertools.product
, itertools.combinations
and the like yield tuples.
how to change that?
Convert the tuples to lists:
combo_all = itertools.combinations_with_replacement(bitcode, 11)
combo_all = map(list, combo_all) # this doesn't iterate over `combo_all`
The code above doesn't loop over anything or store potentially immense amounts of data anywhere (unlike list(combo_all)
). It may not be necessary to store all of the combinations in memory at once, so you may be better off iterating over each of them without storing all of them (in case you're searching for a particular combination or writing them line by line to a file).
If you need to have all of the combinations in memory, convert combo_all
to a list:
combo_all = list(combo_all)
Upvotes: 1