简体   繁体   中英

Python Enumerate: Is it the enumerate object released after usage?

I recently discovered enumerate to make it easier to identify index and value. However, I noticed an odd usage. If you declare an enumerate object and use it in any way, the data inside the object disappears afterward.

What is happening here?

In a simple example, you declare an object with an enumerated list. You convert it back to a list once. On the second try, it is empty.

A = [1, 2, 3, 4]
enuObject = enumerate(A)
>>> list(enuObject)
[(0, 1), (1, 2), (2, 3), (3, 4)]
>>> list(enuObject)
[]

I noticed this when I declared an enumerate call outside of a loop vs in it.

The enumerate object is an iterator, and will be released when the garbage collector finds it's no longer used. However, in this example, the iterator for the enumerate is being completely used by the list function. What this does is very similar to:

items = []
for e in en:
    items.append(e)

return items

It takes every element from the enumeration object en , adds them to a list, and then returns the list when there aren't any items left. So, if you call list again on the fully-consumed enumeration object, the for e in en won't have any items to add to the list, and so it'll just return an empty list.


Iterator

An object representing a stream of data. Repeated calls to the iterator's next() method return successive items in the stream. When no more data are available a StopIteration exception is raised instead. At this point, the iterator object is exhausted and any further calls to its next() method just raise StopIteration again. Iterators are required to have an __iter__() method that returns the iterator object itself so every iterator is also iterable and may be used in most places where other iterables are accepted. One notable exception is code which attempts multiple iteration passes. A container object (such as a list) produces a fresh new iterator each time you pass it to the iter() function or use it in a for loop. Attempting this with an iterator will just return the same exhausted iterator object used in the previous iteration pass, making it appear like an empty container.


This is in the Python document. So basically it is intentionally designed that way.

In short words, When you reach to the end of an iterator, StopIteration is being raised.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM