Does enumerate() produce a generator object?

前端 未结 5 918
温柔的废话
温柔的废话 2020-12-06 03:55

As a complete Python newbie, it certainly looks that way. Running the following...

x = enumerate([\'fee\', \'fie\', \'foe\'])
x.next()
# Out[1]: (0, \'fee\')         


        
5条回答
  •  悲&欢浪女
    2020-12-06 04:36

    While the Python documentation says that enumerate is functionally equivalent to:

    def enumerate(sequence, start=0):
        n = start
        for elem in sequence:
            yield n, elem
            n += 1
    

    The real enumerate function returns an iterator, but not an actual generator. You can see this if you call help(x) after doing creating an enumerate object:

    >>> x = enumerate([1,2])
    >>> help(x)
    class enumerate(object)
     |  enumerate(iterable[, start]) -> iterator for index, value of iterable
     |  
     |  Return an enumerate object.  iterable must be another object that supports
     |  iteration.  The enumerate object yields pairs containing a count (from
     |  start, which defaults to zero) and a value yielded by the iterable argument.
     |  enumerate is useful for obtaining an indexed list:
     |      (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
     |  
     |  Methods defined here:
     |  
     |  __getattribute__(...)
     |      x.__getattribute__('name') <==> x.name
     |  
     |  __iter__(...)
     |      x.__iter__() <==> iter(x)
     |  
     |  next(...)
     |      x.next() -> the next value, or raise StopIteration
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  __new__ = 
     |      T.__new__(S, ...) -> a new object with type S, a subtype of T
    

    In Python, generators are basically a specific type of iterator that's implemented by using a yield to return data from a function. However, enumerate is actually implemented in C, not pure Python, so there's no yield involved. You can find the source here: http://hg.python.org/cpython/file/2.7/Objects/enumobject.c

提交回复
热议问题