Iterators and generators
A for loop works with anything iterable: lists, strings, ranges, dictionaries. Behind the scenes it asks the object for one value at a time.
A generator is the simplest way to make your own iterable. It looks like a function, but uses yield instead of return:
def even_numbers(limit):
n = 0
while n < limit:
yield n
n += 2
for x in even_numbers(7):
print(x) # 0, 2, 4, 6
Each yield hands one value to the loop and pauses the function. When the loop asks for the next value, the function carries on from where it paused.
Why bother?
Generators produce values lazily, one at a time, so they use almost no memory, even for huge or endless sequences:
def naturals():
n = 1
while True: # never ends, and that is fine
yield n
n += 1
You take only what you need, for example with itertools.islice(naturals(), 5).
Generator expressions
Like a list comprehension, but in round brackets: (n * n for n in range(10)). Passed straight to sum, max or any, it never builds the full list.
Your task
countdown(n): a generator yieldingn,n - 1, ...,1.fibonacci(): an endless generator of Fibonacci numbers: 0, 1, 1, 2, 3, 5...chunks(items, size): yields consecutive lists ofsizeitems (the last may be shorter).total_even_squares(limit): the sum ofn * nfor every evennbelowlimit, using a generator expression.