Reputation: 1098
I'm using itertools
to generate all possible permutations of a list. I would like it to return a list of lists, but this is not what I'm getting.
For example
import itertools
print list(itertools.permutations([1, 2]))
returns
>>> [(1, 2), (2, 1)]
But I was expecting
>>> [[1, 2], [2, 1]]
Is it possible?
Upvotes: 8
Views: 5830
Reputation: 1122222
Just map your tuples to lists:
import itertools
try:
# Python 2, use Python 3 iterator version of map
from future_builtins import map
except ImportError:
# already using Python 3
pass
map(list, itertools.permutations([1, 2]))
In Python 3, map()
is an iterator too, so the tuples are converted to lists as you iterate.
I'm assuming here that you don't need the full permutations result in one go. You can always call list()
on the map()
, or use a list comprehension instead if you do:
[list(t) for t in itertools.permutations([1, 2])]
or for Python 2, just drop the from future_builtins
import and leave map
to produce a list.
Upvotes: 8
Reputation: 23192
You can use a list comprehension to convert each tuple to a list and collect the results in a list:
>>> [list(p) for p in itertools.permutations([1, 2])]
[[1, 2], [2, 1]]
Upvotes: 7