Python Forum
Calling list() on permutation - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Calling list() on permutation (/thread-16463.html)



Calling list() on permutation - trevorkavanaugh - Mar-01-2019

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 []



RE: Calling list() on permutation - ichabod801 - Mar-01-2019

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.


RE: Calling list() on permutation - trevorkavanaugh - Mar-01-2019

(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!