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

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.

Leave a Comment