Yield Statement in Python

Yield Statement in Python

The yield statement is a special kind of function in Python. It’s useful when processing complex data structures. It is used in generators. This function keeps the same data without using global variables as in an ordinary function. It can interact with the for statement. We work only with sequences like strings, tuples, and lists.

The simple example of a generator with yield function:

>>> def city():
…     yield(“Warsaw”)
…     yield(“Moscow”)

>>> city()
<generator object city at 0x00C7A5D0>

We have the generator with two items(“Warsaw” and “Moscow”). Now, we must create a iterator for this generator:

>>> print(next(x))
>>> print(next(x))
>>> print(next(x))
Traceback (most recent call last):
  File “<stdin>”, line 1, in <module>

If you see a yield statement in a function, the function is a generator object. We use the next() function in the iterator to get an item from our generator.The yield function returns data. Each time next() is called in our iterator, the generator can resume where it finished. It really remember all values an the statement that was last executed.

def func_name(param1, param2,…)


The suite of statements must include at least one yield statement. The yield statement specifies the values emitted by the generator. Note that the expression is required.

yield expr

When we see a return statement in a function, we should know that it ends our generator with StopIteration exception. The return statement have no return value with itself. We’ll see why:

def bolo():

yield 1

yield 2

yield 3

yield 4


Now, we can iterate:

>>> for x in bolo():
…     print(x)


The return statement in our generator returns all values that where associated with the yield statement,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s