Python Forum
Calling list() on permutation
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Calling list() on permutation
#1
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 []
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
(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!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question How to print each possible permutation in a dictionary that has arrays as values? noahverner1995 2 1,695 Dec-27-2021, 03:43 AM
Last Post: noahverner1995
  Even/Odd permutation braankoo 9 11,499 Jan-10-2021, 01:19 AM
Last Post: Larz60+
  Help with calling list from user input farispython 5 2,748 Nov-03-2019, 03:13 PM
Last Post: Gribouillis
  memory error using permutation list of 11 elements kikidog 1 3,844 Sep-10-2019, 08:22 PM
Last Post: ichabod801
  how to get all the possible permutation and combination of a sentence in python sodmzs 1 4,120 Jun-13-2019, 07:02 AM
Last Post: perfringo
  Permutation help. jarrod0987 1 2,158 Jun-28-2018, 04:44 PM
Last Post: ichabod801
  Calling list from previous function zykbee 1 2,919 Nov-13-2017, 12:10 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020