What does it mean to “consume” in Python? In an iterator?

前端 未结 6 728
既然无缘
既然无缘 2020-12-11 01:45

I have been working in Python for a few months now, and it has occurred to me that I often overlook vocabulary that escapes me at first glance, instead trying to get the gis

6条回答
  •  既然无缘
    2020-12-11 02:28

    The term "consume" is an informal term that refers to the way iterators work in Python. An "iterator" is a single object that is responsible for creating some sequence of elements. This sequence might be elements of an existing list, or it might be something calculated, like prime numbers or the decimal digits of π.

    When a caller asks for the "next" item from an iterator, the iterator provides the next item and then changes its own state so it's ready to produce the next item after that. This usually is what you expect.

    If I have a generator that produces the sequence of increasing prime numbers, the first time I call it I will get 2 in return. The next time, I'll get 3. If I then give you a reference to that generator, you'll call it (for what you think is the first time) and get 5. There isn't any way to "reset" the generator so it will start at 2 again, except by creating a completely new instance of the generator. In that situation, I could say that I have already consumed the first two items before giving you the generator.

提交回复
热议问题