@@ -85,8 +85,8 @@ flow control is continued with ``x`` being set to the next entry in the list.
8585After the first matching integer is found, the loop is terminated with the
8686``break `` statement.
8787
88- Loops with an index
89- -------------------
88+ `` for `` Loops with an index
89+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
9090
9191You can also output the index in a ``for `` loop, for example with
9292:py:func: `enumerate() `:
@@ -102,7 +102,7 @@ You can also output the index in a ``for`` loop, for example with
102102 2 Lists
103103
104104 List Comprehensions
105- -------------------
105+ ~~~~~~~~~~~~~~~~~~~
106106
107107A list is usually generated as follows:
108108
@@ -153,14 +153,50 @@ appended to the end of the expression:
153153 >>> squares
154154 [16, 25, 36, 49]
155155
156+ Dict Comprehensions
157+ ~~~~~~~~~~~~~~~~~~~
158+
159+ They create a key-value pair for each index and the corresponding list element:
160+
161+ .. code-block :: pycon
162+
163+ >>> data_types = ["Data types", "Numbers", "Lists"]
164+ >>> data_types = {index: value for index, value in enumerate(data_types)}
165+ >>> data_types
166+ {0: 'Data types', 1: 'Numbers', 2: 'Lists'}
167+
168+ Change a ``Collection ``
169+ ~~~~~~~~~~~~~~~~~~~~~~~
170+
171+ Modifying a ``collection `` while iterating over it can be difficult. Therefore,
172+ a copy of the ``collection `` is often modified instead:
173+
174+ .. code-block :: pycon
175+
176+ >>> for index, title in data_types.items():
177+ ... if index == 0:
178+ ... del data_types[index]
179+ ...
180+ Traceback (most recent call last):
181+ File "<python-input-2>", line 1, in <module>
182+ for index, title in data_types.items():
183+ ~~~~~~~~~~~~~~~~^^
184+ RuntimeError: dictionary changed size during iteration
185+ >>> for index, title in data_types.copy().items():
186+ ... if index == 0:
187+ ... del data_types[index]
188+ ...
189+ >>> data_types
190+ {1: 'Numbers', 2: 'Lists'}
191+
156192 Checks
157193------
158194
159195* Removes all negative numbers from the list ``x = [ -2, -1, 0, 1, 2, 3] ``.
160196
161197* Which list comprehension would you use to achieve the same result?
162198
163- * How would you count the total number of negative numbers in the list ``[-[ 1,
199+ * How would you count the total number of negative numbers in the list ``[[- 1,
164200 0, 1], [-1, 1, 3], [-2, 0, 2]] ``?
165201
166202* Creates a generator that only returns odd numbers from 1 to 10.
0 commit comments