Click to Flip Card
Generator
What is an interator? What is a generator? Are square brackets use for generators?
![](/lib/images/knowledge_graph.png)
Iterator
"""
Many objects in Python support iteration.
They are using iteration protocol, a generic way to make objects iterable.
An interator is any object that will yield objects when used in a loop context.
"""
# Loop context
dict = {'a':1, 'b': 2, 'c': 3}
for key in dict:
print(key)
# a (yield, iterator object caled)
# b
# c
# Iterator object
itr = iter(dict)
print(itr)
# <dict_keyiterator object at 0x00000274B8582900>
# Loop equivalent
print(next(itr)) # a
print(next(itr)) # b
print(next(itr)) # c
Generator
"""
A normal function execute and return a single result at a time.
A generator can return a sequence of values by pausing and resuming execution.
"""
# Functions return values
def squares_func():
lst = []
for i in range(1, 10):
m = i**2
lst.append(m)
return lst
print("\nLooping through the function returned value:")
A = squares_func()
for x in A:
print(x, end=' ')
# 1 4 9 16 25 36 49 64 81 100
# Generators yield values
def squares_gen():
for i in range(1, 10):
yield i**2
print("\nLooping using iter object:")
G = squares_gen()
itr = iter(G)
for i in range(0, 3):
print(next(itr), end=' ')
# 1 4 9
Generator expressions
"""
Generator expressions is similar to list, dictionary or set comprehension.
Enclose withing parantheses insteed of brackets
"""
gen = (x**2 for x in range(100))
print(next(gen)) # 0
print(next(gen)) # 1
print(next(gen)) # 4
# This is equivalent to the more verbose generator:
def make_gen():
for x in range(100):
yield x**2
gen = make_gen()
print(next(gen)) # 0
print(next(gen)) # 1
print(next(gen)) # 4
Last update: 8 days ago