summaryrefslogtreecommitdiffstats
path: root/Doc/tutorial
diff options
context:
space:
mode:
authorGeorg Brandl <georg@python.org>2007-12-14 19:03:36 (GMT)
committerGeorg Brandl <georg@python.org>2007-12-14 19:03:36 (GMT)
commitadbda844d0782a64a278561f08bdf7b0d8218bdb (patch)
treec12b6fdba4df1f10bf255a24e39068c2283c30da /Doc/tutorial
parent366523c6671b4648382d19e791a1d98fd70e87b5 (diff)
downloadcpython-adbda844d0782a64a278561f08bdf7b0d8218bdb.zip
cpython-adbda844d0782a64a278561f08bdf7b0d8218bdb.tar.gz
cpython-adbda844d0782a64a278561f08bdf7b0d8218bdb.tar.bz2
Add a section about nested listcomps to the tutorial.
Thanks to Ian Bruntlett and Robert Lehmann.
Diffstat (limited to 'Doc/tutorial')
-rw-r--r--Doc/tutorial/datastructures.rst42
1 files changed, 42 insertions, 0 deletions
diff --git a/Doc/tutorial/datastructures.rst b/Doc/tutorial/datastructures.rst
index a559956..c243fe3 100644
--- a/Doc/tutorial/datastructures.rst
+++ b/Doc/tutorial/datastructures.rst
@@ -265,6 +265,48 @@ to complex expressions and nested functions::
['3.1', '3.14', '3.142', '3.1416', '3.14159']
+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.
+
+Consider the following example of a 3x3 matrix held as a list containing three
+lists, one list per row::
+
+ >>> mat = [
+ ... [1, 2, 3],
+ ... [4, 5, 6],
+ ... [7, 8, 9],
+ ... ]
+
+Now, if you wanted to swap rows and columns, you could use a list
+comprehension::
+
+ >>> print [[row[i] for row in mat] for i in [0, 1, 2]]
+ [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
+
+Special care has to be taken for the *nested* list comprehension:
+
+ To avoid apprehension when nesting list comprehensions, read from right to
+ left.
+
+A more verbose version of this snippet shows the flow explicitly::
+
+ for i in [0, 1, 2]:
+ for row in mat:
+ print row[i],
+ print
+
+In real world, you should prefer builtin functions to complex flow statements.
+The :func:`zip` function would do a great job for this use case::
+
+ >>> zip(*mat)
+ [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
+
+See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.
+
.. _tut-del:
The :keyword:`del` statement