# Sequences as conventional interfaces def fib(n): if n == 0: return 0 elif n == 1: return 1 return fib(n - 1) + fib(n - 2) is_even = lambda x: x % 2 == 0 fibs = tuple(map(fib, range(8))) even_fibs = tuple(filter(is_even, fibs)) sum(even_fibs) # Generator expressions even_fibs2 = tuple(fib(n) for n in range(8) if is_even(fib(n))) # Reducing a sequence from operator import mul from functools import reduce reduce(mul, (1, 2, 3, 4, 5), 1) def accumulate(combiner, start, n, term): """Accumulate a sequence of n terms with the given combiner and initial value. >>> accumulate(mul, 1, 4, lambda x: x * x) 576 """ return reduce(combiner, map(term, range(1, n + 1)), start) # More functions on iterables (bonus) a, b = (1, 2, 3), (4, 5, 6, 7) for x, y in zip(a, b): print(x + y) from itertools import product, combinations tuple(product(a, b[:2])) tuple(combinations(a, 2)) # Lists a = [3, 1, 2] b = sorted(a) c, d = a, a[:] c[0] = 4 d[0] = 5 a[1:2] = [7, 8, 9] # Objects type(4) type([4]) (4).real, (4).imag [1, 2, 1, 4].count(1) [1, 2, 1, 4] is [1, 2, 1, 4] [1, 2, 1, 4] == [1, 2, 1, 4] e, f = 1e12, 1e12 e is f True e = 1e12 f = 1e12 e is f # List comprehensions g = [3 / x for x in range(4) if x != 0] # Dictionaries eras = {'cain': 2.79, 'bumgarner': 3.37, 'vogelsong': 3.37, 'lincecum': 5.18, 'zito': 4.15} total_era = 0 for pitcher in eras: total_era += eras[pitcher] total_era / len(eras) eras['lincecum'] = 3.0 new_eras = {p: round(eras[p]-1, 3) for p in eras}