Iterator & Generator

Iterator

The iterator objects themselves are required to support the following two methods, which together form the iterator protocol:

iterator.__iter__()

Return the iterator object itself. This is required to allow both containers and iterators to be used with the forarrow-up-rightand inarrow-up-right statements. This method corresponds to the tp_iterarrow-up-right slot of the type structure for Python objects in the Python/C API.

iterator.__next__()

Return the next item from the container. If there are no further items, raise the StopIterationarrow-up-right exception. This method corresponds to the tp_iternextarrow-up-right slot of the type structure for Python objects in the Python/C API.

Generator

Generator 是一种特殊的 iterator。

Generator Expressions

a = [1,2,3]
gen = (x for x in a)

Yield Expressions

yield 表达式可以拥有值。

generator.__next__()

Starts the execution of a generator function or resumes it at the last executed yield expression.

generator.send(value)

Resumes the execution and “sends” a value into the generator function. The value argument becomes the result of the current yield expression. The send()arrow-up-right method returns the next value yielded by the generator, or raises StopIterationarrow-up-right if the generator exits without yielding another value.

If a container object’s __iter__()arrow-up-right method is implemented as a generator, it will automatically return an iterator object (technically, a generator object) supplying the __iter__()arrow-up-right and __next__()arrow-up-right methods.

When yield from <expr> is used, the supplied expression must be an iterable. The values produced by iterating that iterable are passed directly to the caller of the current generator’s methods.

Reference

[1] https://docs.python.org/3/library/stdtypes.html#iterator-typesarrow-up-right

[2] https://docs.python.org/3/reference/expressions.html#generator-expressionsarrow-up-right

Last updated

Was this helpful?