PythonSyntax and keywords
yield
Creates a generator: a function that returns successive values on demand.
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 valueGood 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
#- returnEnds a function and returns a value to the place it was called from.
- forA loop that goes through the successive items of a sequence or other iterable object.
- List comprehensionsA concise way to build lists, sets, and dictionaries from other collections.
- iter()Returns an iterator for a collection, an object that hands out its items one at a time. This is the mechanism behind the for loop.
- next()Fetches the next item from an iterator. Once it is exhausted, returns a default value or raises StopIteration.
Spotted a mistake or missing an example? Write to us.