cpython: 132158b287d7 (original) (raw)
--- a/Doc/tutorial/datastructures.rst
+++ b/Doc/tutorial/datastructures.rst
@@ -235,89 +235,139 @@ and works exactly like this.
List Comprehensions
-------------------
-List comprehensions provide a concise way to create lists without resorting to
-use of :func:map
, :func:filter
and/or :keyword:lambda
. The resulting list
-definition tends often to be clearer than lists built using those constructs.
-Each list comprehension consists of an expression followed by a :keyword:for
-clause, then zero or more :keyword:for
or :keyword:if
clauses. The result
-will be a list resulting from evaluating the expression in the context of the
-:keyword:for
and :keyword:if
clauses which follow it. If the expression
-would evaluate to a tuple, it must be parenthesized. ::
+List comprehensions provide a concise way to create lists.
+Common applications are to make new lists where each element is the result of
+some operations applied to each member of another sequence or iterable, or to
+create a subsequence of those elements that satisfy a certain condition.
+
+For example, assume we want to create a list of squares, like::
+
+We can obtain the same result with:: +
+This is also equivalent to squares = map(lambda x: x**2, range(10))
,
+but it's more concise and readable.
+
+A list comprehension consists of brackets containing an expression followed
+by a :keyword:for
clause, then zero or more :keyword:for
or :keyword:if
+clauses. The result will be a new list resulting from evaluating the expression
+in the context of the :keyword:for
and :keyword:if
clauses which follow it.
+For example, this listcomp combines the elements of two lists if they are not
+equal::
- ... for y in [3,1,4]:
- ... if x != y:
- ... combs.append((x, y))
- ...
- [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] +
+Note how the order of the :keyword:for
and :keyword:if
statements is the
+same in both these snippets.
+
+If the expression is a tuple (e.g. the (x, y)
in the previous example),
+it must be parenthesized. ::
+
create a new list with the values doubled
- [-8, -4, 0, 4, 8]
filter the list to exclude negative numbers
- [0, 2, 4]
apply a function to all the elements
- [4, 2, 0, 2, 4]
call a method on each element
freshfruit = [' banana', ' loganberry ', 'passion fruit '] [weapon.strip() for weapon in freshfruit] ['banana', 'loganberry', 'passion fruit']
- [6, 12, 18]
- [12, 18]
- []
- [[2, 4], [4, 16], [6, 36]]
File "<stdin>", line 1, in ?[](#l1.87)
[x, x**2 for x in vec][](#l1.88)
create a list of 2-tuples like (number, square)
- [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
the tuple must be parenthesized, otherwise an error is raised
File "<stdin>", line 1[](#l1.94)
SyntaxError: invalid syntax[x, x**2 for x in range(6)][](#l1.95) ^[](#l1.96)
- [(2, 4), (4, 16), (6, 36)]
- [8, 6, -18, 16, 12, -36, 24, 18, -54]
- [6, 5, -7, 8, 7, -5, 10, 9, -3]
- [8, 12, -54]
-List comprehensions are much more flexible than :func:map
and can be applied
-to complex expressions and nested functions::
+List comprehensions can contain complex expressions and nested functions::
Nested List Comprehensions --------------------------- +'''''''''''''''''''''''''' -If you've got the stomach for it, list comprehensions can be nested. They are a -powerful tool but -- like all powerful tools -- they need to be used carefully, -if at all. +The initial expression in a list comprehension can be any arbitrary expression, +including another list comprehension. + +Consider the following example of a 3x4 matrix implemented as a list of +3 lists of length 4:: -Consider the following example of a 3x3 matrix held as a list containing three -lists, one list per row::
+The following list comprehension will transpose rows and columns:: +
+As we saw in the previous section, the nested listcomp is evaluated in
+the context of the :keyword:for
that follows it, so this example is
+equivalent to::
-Now, if you wanted to swap rows and columns, you could use a list
-comprehension::
- ... transposed.append([row[i] for row in matrix])
- ...
- [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
- -Special care has to be taken for the nested list comprehension: +which, in turn, is the same as::
- -A more verbose version of this snippet shows the flow explicitly::
- ... # the following 3 lines implement the nested listcomp
- ... transposed_row = []
- ... for row in matrix:
- ... transposed_row.append(row[i])
- ... transposed.append(transposed_row)
- ...
- [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
-In real world, you should prefer built-in functions to complex flow statements.
+In the real world, you should prefer built-in functions to complex flow statements.
The :func:zip
function would do a great job for this use case::
See :ref:tut-unpacking-arguments
for details on the asterisk in this line.