2
0
mirror of https://github.com/chubin/cheat.sheets synced 2024-11-15 06:12:59 +00:00
cheat.sheets/sheets/_python3/generator
2021-06-08 20:42:25 +01:00

20 lines
561 B
Plaintext

# Declare a function that behaves like an iterator.
# Any function with yield 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:
yield 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