The yield keyword in Python

To understand how yield works, you need to understand iterables, iterators, and generators


An iterable is an object capable of returning its members one at a time. Iterables include:
All sequence types, such as:

  • list
  • str
  • tuple

Some none-sequence types, such as:

  • dict
  • file objects
  • any objects of user-defined classes with an __iter__() method or with a __getitem__() method that implements Sequence
    semantics (see below)

Iterables can be used in a for loop and in many other places where a sequence is needed:

  • zip()
  • map()

When an iterable object is passed to the built-in function iter(), it returns an iterator for the object.
The iterator is good for one pass over the set of values
It is usually not necessary to call iter() directly, as the for statement does this for you, creating a temporary unnamed
variable to hold the iterator for the duration of the loop.

User-defined iterables need to define one of __iter__() or __getitem__().

Called when an iterator is required for a container.
Iterator objects also need to implement this method; they are required to return themselves.

Called to implement self[key].
For sequence types, the accepted keys should be integers or slice objects.
The interpretation of negative slices is the responsibility of the __getitem__() method.
If key is of the wrong type, a TypeError may be raised.
If the key is of a value outside the set of indexes for the sequence, an IndexError should be raised.
For mapping types, if key is missing, a KeyError should be raised.


An iterator is an object representing a stream of data.
Calls to the object’s __next__() method (or passing it to the built-in function next()) return successive items in the
When no more data are available, a StopIteration exception is raised.
The iterator is then exhausted, and any subsequent calls to __next__() method will raise a StopIteration again.
Iterators are required to have an __iter__() method so every iterator is also iterable and may be used in most places where
other iterables are accepted.


The word generator refers to two things: a generator function and a generator iterator.

Generator function
A generator function is like a normal function except that it contains one or more yield expressions.
When a generator function is called, its code is not executed, and instead it returns a generator iterator.

Generator iterator
This is an iterator that controls the execution of the generator function in response to calls to the next() function.
Each yield in the associated generator function causes execution to be temporarily suspended. When the iterator resumes, execution continues from where it left off.