4 List comprehensions are declarative ways of defining lists in python. The
5 following ways of building a list are equivalent:
9 l = [x**2 for x in range(1, 10)]
12 for x in range(1, 10):
15 .. code-block:: python
17 m = [x for x in range(1, 10) if x % 2 == 1]
20 for x in range(1, 10):
24 .. code-block:: python
26 n = [(x, y) for x in range(1, 10) for y in range(1, 10) if x > y]
29 for x in range(1, 10):
30 for y in range(1, 10):
36 .. code-block:: python
38 [expression for x in y condition]
41 Dictionary Comprehensions
42 =========================
44 Dictionary comprehensions are the analogous construct for dictionaries:
46 .. code-block:: python
48 o = {x: x**3 for x in range(1, 100) if math.sqrt(x).is_integer()}
51 for x in range(1, 100):
52 if math.sqrt(x).is_integer():
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.
61 A generator is a function that yields values rather than returning them. For
64 .. code-block:: python
72 The built in `range` function is similar to a generator. Generators are iterable:
74 .. code-block:: python
76 for square in squares():
83 Generators can take arguments:
85 .. code-block:: python
95 Generator expressions are similar to list comprehensions:
97 .. code-block:: python
99 squares = (i**2 for i in range(10000))
101 Generators are lazy, values are calculated when needed, meaning they can represent
102 infinite sequences without requiring infinite memory.