Iterables and iterators
- An iterable can be looped over (
list,str,dict,file) - An iterator produces items one at a time with
next() iter(iterable)gives an iterator;next()raisesStopIterationat the end — aforloop handles this for you
Generators
A generator function uses yield instead of return. Each yield hands out one value and pauses the function until the next value is requested.
Why generators?
- Memory efficient — values are made one at a time, not stored in a big list
- Can represent endless sequences
- Great for reading huge files line by line or streaming data
Generator expressions
(x * x for x in range(10)) — like a list comprehension with round brackets.
yield from
Passes along all values from another iterable.
itertools
count, cycle, islice (take the first n), chain, groupby, combinations, permutations, product, accumulate.
Example
Example — Generators in practice
Python
import itertools
def countdown(n):
while n > 0:
yield n
n -= 1
print(list(countdown(5)))
def fibonacci():
a, b = 0, 1
while True: # endless, but only computed on demand
yield a
a, b = b, a + b
print(list(itertools.islice(fibonacci(), 10)))
def read_large_log(lines):
for line in lines: # with a real file: for line in open(path)
if "ERROR" in line:
yield line.strip()
log = ["INFO start", "ERROR db down", "INFO retry", "ERROR timeout"]
for err in read_large_log(log):
print(err)
gen = countdown(2)
print(next(gen), next(gen))
print(list(itertools.combinations("ABC", 2)))
Output: [5, 4, 3, 2, 1], the first 10 Fibonacci numbers [0, 1, 1, 2, 3, 5, 8, 13, 21, 34], the two ERROR lines, 2 1, and [('A', 'B'), ('A', 'C'), ('B', 'C')].