Search code examples
python-3.xenumeration

What is a happening with this enumeration


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

Solution

  • 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.