REMEMBER PYTHON

# MINTE9 2REMEMBER

Last update:   23-07-2021

### Generators

p330 ! 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.
 RunCode
g = (x**2 for x in range(3))

print(next(g)) # 0
print(next(g)) # 1
print(next(g)) # 4

print(next(g)) # StopIteration Exception
... 5 lines˄˄˄
p330 You can also use a for loop to iterate through values. The generator object keeps track of where it is in the sequence.
 RunCode
g = (x**2 for x in range(3))

for val in g:
print(val) # invoke __next__

next(g) # StopIteration Exception
... 4 lines˄˄˄
Generators are often used with functions like sum, max, min.
 RunCode
sum = sum(x**2 for x in range(5))

print(sum) # 30
... 2 lines˄˄˄

Questions
CARD
31
32

A B C D E F
🔔
1/2