2

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!

3 Answers 3

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Many thanks to both of you! Apologies for the incomplete question, I intended to copy in precisely what you indicated.
@Jared No problem at all, and welcome to the site :) If either answer helped you, you can click the little check mark next to that answer's score to 'accept' it. This indicates that an answer solved your problem and essentially marks a question as complete. Good luck with everything!
1

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__()

Comments

0
from itertools import permutations

#iteration
for p in permutations([1,2,3]):
    print(p)

This should work perfectly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.