0

In this code, I make list of days and then make an enumerate object from it. When I convert this to a list I get an expected result.

What is happening to the my_enumerate_object when I do

list(my_enumerate_object)

The second time I get an empty list? Is this garbage collection in operation?

my_list = ["Monday",
       "Tuesday",
       "Wednesday",
       "Thursday",
       "Friday",
       "Saturday",
       "Sunday"]


my_enumerate_object = enumerate(my_list)

# I can make a list from my_enumerate_object
list(my_enumerate_object)
Out[14]: 
[(0, 'Monday'),
 (1, 'Tuesday'),
 (2, 'Wednesday'),
 (3, 'Thursday'),
 (4, 'Friday'),
 (5, 'Saturday'),
 (6, 'Sunday')]

# but not again
list(my_enumerate_object)
Out[15]: []
nerak99
  • 640
  • 8
  • 26
  • `enumerate` returns an iterator-like object which is a one-shot iterable. Meaning that once you iterate over it you will consume the iterator and there's no way back. This make the object to be very optimized in terms of memory use by not preserving the whole iterable items at once and instead generating each item on demand. – Mazdak May 15 '18 at 17:10
  • Well the dupe police have noticed a question with a potentially searchable subject that is kind of similar. Well done you. – nerak99 May 15 '18 at 17:26
  • Which "dupe" btw is not a duplicate but merely loosely related. (he said: triggering the inevitable downvote). But then, I read the question and the answers. – nerak99 May 15 '18 at 17:30
  • of course I shouldn't have posted a Q to which I did not already know the answer. – nerak99 May 15 '18 at 18:22

1 Answers1

3

Iterating through the enumeration object, as the list constructor does, consumes the enumeration object. Constructing a second list in the same way will require a new enumeration object.

Sneftel
  • 40,271
  • 12
  • 71
  • 104