Skip to content

Commit c1cab07

Browse files
committed
comprehensions: Elucidate and PEP8
* Slightly change wording to make it a little easier to understand * Follow PEP8
1 parent 795bef9 commit c1cab07

1 file changed

Lines changed: 12 additions & 10 deletions

File tree

comprehensions.rst

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ comprehensions in Python:
1010
- dictionary comprehensions
1111
- set comprehensions
1212

13-
``list`` comprehensions were introduced in Python 2. ``set`` and
14-
``dictionary`` comprehensions became a part of Python in version 3.0.
13+
list comprehensions were introduced in Python 2. set and
14+
dictionary comprehensions became a part of Python in version 3.0.
1515

1616
We will discuss them one by one. Once you get the hang of using ``list``
1717
comprehensions then you can use anyone of them easily.
@@ -41,7 +41,7 @@ Here is a short example:
4141
# Output: [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
4242
4343
This can be really useful to make lists quickly. It is even preferred by
44-
some instead of ``filter`` function. ``list`` comprehensions really
44+
some instead of the ``filter`` function. list comprehensions really
4545
shine when you want to supply a list to a method or function to make a
4646
new list by appending to it in each iteration of the ``for`` loop. For
4747
instance you would usually do something like this:
@@ -52,7 +52,7 @@ instance you would usually do something like this:
5252
for x in range(10):
5353
squared.append(x**2)
5454
55-
You can simplify it using ``list`` comprehensions. For example:
55+
You can simplify it using list comprehensions. For example:
5656

5757
.. code:: python
5858
@@ -66,16 +66,18 @@ recently:
6666

6767
.. code:: python
6868
69-
mcase = {'a':10, 'b': 34, 'A': 7, 'Z':3}
70-
71-
mcase_frequency = { k.lower() : mcase.get(k.lower(), 0) + \
72-
mcase.get(k.upper(), 0) for k in mcase.keys() }
73-
69+
mcase = {'a': 10, 'b': 34, 'A': 7, 'Z': 3}
70+
71+
mcase_frequency = {
72+
k.lower(): mcase.get(k.lower(), 0) + mcase.get(k.upper(), 0)
73+
for k in mcase.keys()
74+
}
75+
7476
# mcase_frequency == {'a': 17, 'z': 3, 'b': 34}
7577
7678
In the above example we are combining the values of keys which are same
7779
but in different typecase. I personally do not use ``dict``
78-
comprehensions a lot. You can also quickly reverse a dictionary:
80+
comprehensions a lot. You can also quickly switch keys and values of a dictionary:
7981

8082
.. code:: python
8183

0 commit comments

Comments
 (0)