mirror of
https://github.com/chubin/cheat.sheets
synced 2024-11-12 19:10:26 +00:00
Add python generator and examples
This commit is contained in:
parent
5722e8ecec
commit
7a66371ac2
20
sheets/_python3/generator
Normal file
20
sheets/_python3/generator
Normal file
@ -0,0 +1,20 @@
|
||||
# Declare a function that behaves like an iterator.
|
||||
# Any function with yeild returns generator.
|
||||
# Generators follow lazy evaluation.
|
||||
# lazy evaluation means that the object is evaluated when it is needed,
|
||||
# not when it is created.
|
||||
|
||||
def my_generator(start, end, step=1):
|
||||
while start < end:
|
||||
yeild start
|
||||
start += step
|
||||
|
||||
gen = my_generator(start=1, end=10)
|
||||
next(gen), next(gen), next(gen)
|
||||
# (1, 2, 3)
|
||||
|
||||
gen = (i for i in range(1, 100) if i%2==0)
|
||||
next(gen), next(gen), next(gen), next(gen)
|
||||
# (2, 4, 6, 8)
|
||||
|
||||
# https://wiki.python.org/moin/Generators
|
Loading…
Reference in New Issue
Block a user