2
0
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:
harshal 2021-06-06 23:37:18 +05:30
parent 5722e8ecec
commit 7a66371ac2

20
sheets/_python3/generator Normal file
View 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