In Python, a generator is a type of iterable, like lists or tuples. However, unlike lists, generators do not store their contents in memory. Instead, they generate their content on-the-fly during iteration. One way to create a generator is through the use of the yield
keyword.
Here is an example of how yield
can be used:
main.py56 chars5 lines
This function creates a simple generator that yields
1, 2, and 3 in sequence. When we iterate over this generator, the values are generated on-the-fly:
main.py38 chars3 lines
Output:
main.py6 chars4 lines
Notice that the my_generator
function is paused after each yield
statement until the next iteration is requested. This allows for lazy evaluation of the values, which can be more memory-efficient in some situations.
In summary, the yield
keyword is used to create generators in Python, which allow for lazy evaluation and efficient use of memory.
gistlibby LogSnag