The Python Game Book

code games. learn Python.

User Tools

Site Tools


Sidebar

Github:

en:glossary:g:generators

generators

Generators are functions that use yield instead of (or additionally to) return to return a value. Unlike functions, Generators don't destroy themselves after using: Generators keep their local variables in a “sleeping” state and “wake up” the next time when the generator is called, to proceed with the code after the yield statement.

Generators are a good way to process large chunks of data like files or endless lists, because not the whole list need to be kept in memory, but instead just the generator code.

Generators can also made in a one-liner, like a list_comprehension and are called generator_expressions.

Example for Generator-expressions

>>> a = (x**2 for x in range(10))
>>> a
<generator object <genexpr> at 0x7f4c20cccf90>
>>> a.__next__
<method-wrapper '__next__' of generator object at 0x7f4c20cccf90>
>>> a.__next__()
0
>>> a.__next__()
1
>>> a.__next__()
4
>>> a.__next__()
9

Example for an Generator

def curve(max_value=20):
	x = 1
	while x <= max_value:
		yield x
		x *= 2
#calling
for a in curve():
    print(a)
# ouput
1
2
4
8
16

Weblinks about generators:

 see http://www.dabeaz.com/generators/Generators.pdf
en/glossary/g/generators.txt · Last modified: 2020/12/22 16:57 by horst