Python Forum

Full Version: Calling list() on permutation
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

Whenever I call list() on a permutations object it removes all of the data from the permutations object. Could anyone explain why that is to me?

Example 1:
from itertools import permutations


perm = permutations([1,2,3])

print(list(perm))

print(len(list(perm)))
Output:
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)] 0
Example 2:
from itertools import permutations


perm = permutations([1,2,3])

print(len(list(perm)))

print(list(perm))
Output:
6 []
permutations returns a generator, which is an object that just sits there and generates values until it's done. Once it's done, that's it, it's dead. You can't get anything else out of it. A file object works the same way. You can only read through a file object once, and then it doesn't return anything when you try to read from it.

Note that once you have done list() on the value returned from permutations, you have all the data in the list. You use that instead.
(Mar-01-2019, 05:46 AM)ichabod801 Wrote: [ -> ]permutations returns a generator, which is an object that just sits there and generates values until it's done. Once it's done, that's it, it's dead. You can't get anything else out of it. A file object works the same way. You can only read through a file object once, and then it doesn't return anything when you try to read from it.

Note that once you have done list() on the value returned from permutations, you have all the data in the list. You use that instead.

Ah, okay that makes sense. Thank you for your response!