Programming

  minte9
LearnRemember



Goodies / Generator


Generators

Generators does not compute the values at once, it waits to be asked.
 
# A generator object knows how to iterate a sequence of values.
#
# Unlike list, ...
# it does not compute the values at once, ...
# it waits to be asked.
#
# A generator expression are similar with list comprehesion,
# but with parantheses instead of square brakets


# Generator

g = (x**2 for x in range(3))
assert next(g) == 0
assert next(g) == 1
assert next(g) == 4
next(g) # StopIteration - Exception


# Populate a list using generator
# only once at a time

list = []
g = (x**2 for x in range(101010))
list.append(next(g))
list.append(next(g))
assert len(list) == 2
assert len(list) != 101010


# Populate a list using for loop
# automatically invokes __next__ generator

list = []
for x in range(101010): # __next__
    list.append(x)

assert len(list) != 1
assert len(list) == 101010

Functions

Generators are often used with functions like sum, max, min.
 
# Generators are often used ...
# with functions like sum, max, min

y = sum(range(5)) # 0 + 1 + 2 + 3 + 4
assert y == 10
assert y != 15

y = sum(x**2 for x in range(5)) # generator
    # 0 + 2 + 4 + 8 + 16
assert y == 30
assert y != 10

y = max([1, 10, 2, 3])
assert y == 10
assert y != 3

y = max(x/2 for x in [10, 50, 20, 30])
assert y == 25.0
assert y != 15.0





References