Does enumerate() produce a generator object?

前端 未结 5 921
温柔的废话
温柔的废话 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:40

    You can try a few things out to prove to yourself that it's neither a generator nor a subclass of a generator:

    >>> x = enumerate(["a","b","c"])
    >>> type(x)
    
    >>> import types
    >>> issubclass(type(x), types.GeneratorType)
    False
    

    As Daniel points out, it is its own type, enumerate. That type happens to be iterable. Generators are also iterable. That second, down-voted answer you reference basically just points that out somewhat indirectly by talking about the __iter__ method.

    So they implement some of the same methods by virtue of both being iterable. Just like lists and generators are both iterable, but are not the same thing.

    So rather than say that something of type enumerate is "generator-like", it makes more sense to simply say that both the enumerate and GeneratorType classes are iterable (along with lists, etc.). How they iterate over data (and shape of the data they store) might be quite different, but the interface is the same.

    Hope that helps!

提交回复
热议问题