yield

Creates a generator: a function that returns successive values on demand.

On this page

Example

#
Python
def levels(start, stop):
    level = start
    while level <= stop:
        yield level, level * 100
        level += 1

for level, exp in levels(1, 3):
    print(f"Level {level}: {exp} EXP")

gen = levels(5, 6)
print(next(gen))
Resultsaved result, you can check it
Level 1: 100 EXP
Level 2: 200 EXP
Level 3: 300 EXP
(5, 500)

Definition and usage

#

A function containing yield becomes a generator. Instead of returning one result and ending, it "pauses" at every yield, hands back a value, and resumes when asked for the next one.

Generators produce items lazily, one after another. Thanks to this, you can process very large data, for example the lines of a huge file, without loading everything into memory, and even describe infinite sequences.

You go through a generator with a for loop, or fetch successive values with the next() function. The notation yield from other passes along every value of another generator or collection.

Syntax

#
Syntax
def generator():
    yield value

Good practices

#
  • A generator can only be traversed once. If you need the data several times, convert it to a list with list().
  • For simple generators, a generator expression is enough: (x * x for x in numbers).

Related entries

#

Spotted a mistake or missing an example? Write to us.