Python Generators: Difference between revisions
Jump to navigation
Jump to search
Line 26: | Line 26: | ||
print(x) | print(x) | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=Generator | =Generator Comprehensions= | ||
A generator expression is the generator analogues to [[Python_Comprehensions#List_Comprehensions|list]], [[Python_Comprehensions#Dictionary_Comprehensions|dictionary]] and [[Python_Comprehensions#Set_Comprehensions|set]] comprehensions. | A generator expression is the generator analogues to [[Python_Comprehensions#List_Comprehensions|list]], [[Python_Comprehensions#Dictionary_Comprehensions|dictionary]] and [[Python_Comprehensions#Set_Comprehensions|set]] comprehensions. | ||
Revision as of 19:07, 17 May 2024
Internal
TODO
- PROCESS IPy Generators Page 101.
- PROCESS PyOOP "Generator expressions"
- PROCESS PyOOP "Generators" + "Yield items from another iterable"
Overview
A generator is a way to construct a new iterable object. Whereas normal functions execute and return a single result at a time, generators can return a sequence of multiple values by pausing and resuming execution each time the generator is used. To create a generator, use the yield
keyword instead of return
in a function.
def squares(n=10):
for i in range(1, n+1):
yield i ** 2
When the generator is called no code is immediately executed:
gen = squares()
It is not until you request elements from the generator that it begins executing code:
for x in gen:
print(x)
Generator Comprehensions
A generator expression is the generator analogues to list, dictionary and set comprehensions.
Use Cases
Create a list with a generator.