You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: source/modules/Comprehensions.rst
+44-1Lines changed: 44 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -88,7 +88,40 @@ Comprehensions and map()
88
88
89
89
Comprehensions are another way of expressing the "map" pattern from functional programming.
90
90
91
-
Python does have a ``map()`` function, which pre-dates comprehensions. But it does much of the same things -- and most folks think comprehensions are the more "Pythonic" way to do it.
91
+
Python does have a ``map()`` function, which pre-dates comprehensions. But it does much of the same things -- and most folks think comprehensions are the more "Pythonic" way to do it. And there is nothing that can be expressed with ``map()`` that cannot be done with a comprehension. IF youare not familiar with ``map()``, you can saftly skip this, but if you are:
92
+
93
+
.. code-block:: python
94
+
95
+
map(a_function, an_iterable)
96
+
97
+
is the same as:
98
+
99
+
.. code-block:: python
100
+
101
+
[a_function(item), for item in an_iterable]
102
+
103
+
In this case, the comprehension is a tad wordier than ``map()``. BUt comprehensions really shine when you do'nt already have a handy function to pass to map:
104
+
105
+
.. code-block:: python
106
+
107
+
[x**2for x in an_iterable]
108
+
109
+
To use ``map()``, you need a function:
110
+
111
+
.. code-block:: python
112
+
113
+
defsquare(x):
114
+
return x**2
115
+
116
+
map(square, an_iterable)
117
+
118
+
There are shortcuts of course, including ``lambda`` (stay tuned for more about that):
119
+
120
+
.. code-block:: python
121
+
122
+
map(lambdax: x**2, an_iterable)
123
+
124
+
But is that easier to read or write?
92
125
93
126
94
127
What about filter?
@@ -130,6 +163,8 @@ This is expressing the "filter" pattern and the "map" pattern at the same time -
130
163
131
164
Get creative....
132
165
166
+
How do I see all the built in Exceptions?
167
+
133
168
.. code-block:: python
134
169
135
170
[name for name indir(__builtin__) if"Error"in name]
@@ -431,3 +466,11 @@ If you are going to immediately loop through the items created by the comprehens
431
466
432
467
The "official" term is"generator expression"-- that is what you will see in the Python docs, and a lot of online discussions. I've used the term "generator comprehension" here to better make clear the association with list comprehensions.
433
468
469
+
References
470
+
----------
471
+
472
+
This is a nice intro to comprehensions from Trey Hunner:
0 commit comments