how to use generators python loops code example
Example 1: pytho loops
for x in loop:
print(x)
Example 2: convert generator to list python
g_to_list = list(g) # where g is a generator
Example 3: python generator
# A generator-function is defined like a normal function,
# but whenever it needs to generate a value,
# it does so with the yield keyword rather than return.
# If the body of a def contains yield,
# the function automatically becomes a generator function.
# Python 3 example
def grepper_gen():
yield "add"
yield "grepper"
yield "answer"
grepper = grepper_gen()
next(grepper)
> add
next(grepper)
> grepper
next(grepper)
> answer
Example 4: loop in python
# A Sample Python program to show loop (unlike many
# other languages, it doesn't use ++)
# this is for increment operator here start = 1,
# stop = 5 and step = 1(by default)
print("INCREMENTED FOR LOOP")
for i in range(0, 5):
print(i)
# this is for increment operator here start = 5,
# stop = -1 and step = -1
print("\n DECREMENTED FOR LOOP")
for i in range(4, -1, -1):
print(i)