Reputation: 21
I can't figure out how to get permutations to return the actual permutation and not I tried a lot of different things to no avail. The code I used was from itertools import permutations and then permutations([1,2,3]). Thanks!
Upvotes: 2
Views: 9238
Reputation: 1
from itertools import permutations
#iteration
for p in permutations([1,2,3]):
print(p)
This should work perfectly.
Upvotes: 0
Reputation: 40879
itertools.permutations
is a generator, which means you have to retrieve results from it by using it like this:
for permutation in itertools.permutations([1,2,3]):
do_stuff_with(permutation)
or alternatively put all of them in a list:
list(itertools.permutations([1,2,3]))
or, less conveniently:
generator = itertools.permutations([1,2,3])
generator.__next__()
Upvotes: 1
Reputation: 37279
This may not be answering your question (it appears to be missing the part after 'and not'), but from your code, what you are likely seeing is the repr
of the itertools.permutations
iterator. You can iterate through this object just as you would a normal list in order to access all of the items. If you want to convert it to a list, you can wrap it in list
:
>>> from itertools import permutations
>>> permutations([1, 2, 3])
<itertools.permutations object at 0x1e67890>
>>> list(permutations([1, 2, 3]))
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
However as mentioned above, the iterator can be iterated over just like you would a normal list (the benefit of returning an iterator is that the entire sequence is not loaded into memory right away - it is instead loaded 'as needed'):
>>> for perm in permutations([1, 2, 3]):
... print(perm)
...
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
Upvotes: 2