Skip to content

Commit ccd1695

Browse files
committed
added a bit more about Comprehensions and a reference.
1 parent 43302d0 commit ccd1695

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

source/modules/Comprehensions.rst

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,40 @@ Comprehensions and map()
8888

8989
Comprehensions are another way of expressing the "map" pattern from functional programming.
9090

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**2 for x in an_iterable]
108+
109+
To use ``map()``, you need a function:
110+
111+
.. code-block:: python
112+
113+
def square(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(lambda x: x**2, an_iterable)
123+
124+
But is that easier to read or write?
92125

93126

94127
What about filter?
@@ -130,6 +163,8 @@ This is expressing the "filter" pattern and the "map" pattern at the same time -
130163
131164
Get creative....
132165

166+
How do I see all the built in Exceptions?
167+
133168
.. code-block:: python
134169
135170
[name for name in dir(__builtin__) if "Error" in name]
@@ -431,3 +466,11 @@ If you are going to immediately loop through the items created by the comprehens
431466
432467
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.
433468
469+
References
470+
----------
471+
472+
This is a nice intro to comprehensions from Trey Hunner:
473+
474+
https://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/
475+
476+
Trey writes a lot of good stuff -- I recommned browsing his site.

0 commit comments

Comments
 (0)