PROGRAMMING

# m9/ PYTHON REMEMBERS

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.

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

p330 You can also use a for loop to iterate through values. The generator object keeps track of where it is in the sequence.

g = (x**2 for x in range(3))

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

next(g) # StopIteration Exception

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

sum = sum(x**2 for x in range(5))

print(sum) # 30


Questions

A B C D E F
🔔
1/2