]> git.friedersdorff.com Git - max/comprehensions_and_generators.git/blob - comprehensions_and_generators.rst
Some notes and excercises on generators and comprehensions
[max/comprehensions_and_generators.git] / comprehensions_and_generators.rst
1 List Comprehensions
2 ===================
3
4 List comprehensions are declarative ways of defining lists in python. The 
5 following ways of building a list are equivalent:
6
7 .. code-block:: python
8
9         l = [x**2 for x in range(1, 10)]
10
11         l = []
12         for x in range(1, 10):
13             l.append(x**2)
14
15 .. code-block:: python
16
17         m = [x for x in range(1, 10) if x % 2 == 1]
18
19         m = []
20         for x in range(1, 10):
21             if x % 2 == 1:
22                 m.append(x)
23
24 .. code-block:: python
25
26         n = [(x, y) for x in range(1, 10) for y in range(1, 10) if x > y]
27
28         n = []
29         for x in range(1, 10):
30             for y in range(1, 10):
31                 if x > y:
32                     n.append((x, y))
33
34 The general form is:
35
36 .. code-block:: python
37
38         [expression for x in y condition]
39
40
41 Dictionary Comprehensions
42 =========================
43
44 Dictionary comprehensions are the analogous construct for dictionaries:
45
46 .. code-block:: python
47
48         o = {x: x**3 for x in range(1, 100) if math.sqrt(x).is_integer()}
49
50         o = {}
51         for x in range(1, 100):
52             if math.sqrt(x).is_integer():
53                 o[x] = x**3
54
55 I have never used a dictionary comprehension outside of exercises.  I don't 
56 know how useful they are, and I'm struggling to think of good examples.
57
58 Generators
59 ==========
60
61 A generator is a function that yields values rather than returning them.  For
62 example:
63
64 .. code-block:: python
65
66         def squares():
67             i = 0
68             while True
69                 yield i**2 
70                 i += 1
71
72 The built in `range` function is similar to a generator.  Generators are iterable:
73
74 .. code-block:: python
75
76         for square in squares():
77             print(square)
78             if square > 10000:
79                 break
80
81 But only once!
82
83 Generators can take arguments:
84
85 .. code-block:: python
86
87         def exponents(exp):
88             i = 0
89             while True
90                 yield i**exp
91                 i += 1
92
93
94
95 Generator expressions are similar to list comprehensions:
96
97 .. code-block:: python
98
99         squares = (i**2 for i in range(10000)) 
100
101 Generators are lazy, values are calculated when needed, meaning they can represent
102 infinite sequences without requiring infinite memory.