Skip to content

Commit 8578308

Browse files
authored
Doc: clarify distinction between nested listcomps and multi-for listcomps
In section 5.1.3, the flatten example uses a single list comprehension with two `for` clauses. In section 5.1.4, the actual nested list comprehension (a comprehension whose expression is itself a comprehension) is introduced. The current wording creates two problems: 1. The flatten example in 5.1.3 has no label distinguishing it from a "nested" comprehension, so readers may already think they've seen nesting before reaching 5.1.4. 2. Section 5.1.4 opens with "As we saw in the previous section...", implying the two constructs are the same idea continued, rather than two distinct concepts. This commit: - Adds "single ... with two 'for' clauses" to the flatten comment in 5.1.3 to preemptively distinguish it. - Rewrites the opening sentence of the 5.1.4 explanation to explicitly contrast the two constructs and clarify what makes a list comprehension truly "nested".
1 parent c6f7368 commit 8578308

1 file changed

Lines changed: 7 additions & 4 deletions

File tree

Doc/tutorial/datastructures.rst

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,7 @@ it must be parenthesized. ::
265265
[x, x**2 for x in range(6)]
266266
^^^^^^^
267267
SyntaxError: did you forget parentheses around the comprehension target?
268-
>>> # flatten a list using a listcomp with two 'for'
268+
>>> # flatten a list using a single listcomp with two 'for' clauses
269269
>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
270270
>>> [num for elem in vec for num in elem]
271271
[1, 2, 3, 4, 5, 6, 7, 8, 9]
@@ -296,9 +296,12 @@ The following list comprehension will transpose rows and columns::
296296
>>> [[row[i] for row in matrix] for i in range(4)]
297297
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
298298

299-
As we saw in the previous section, the inner list comprehension is evaluated in
300-
the context of the :keyword:`for` that follows it, so this example is
301-
equivalent to::
299+
Unlike a list comprehension with multiple ``for`` clauses (as seen in
300+
the previous section), here the expression itself is a complete list
301+
comprehension — this is what makes it *nested*. The inner list
302+
comprehension ``[row[i] for row in matrix]`` is evaluated once for
303+
each value of ``i`` in the outer :keyword:`for`, so this example is
304+
equivalent to:
302305

303306
>>> transposed = []
304307
>>> for i in range(4):

0 commit comments

Comments
 (0)