[New-bugs-announce] [issue13549] Incorrect nested list comprehension documentation

Matt Long report at bugs.python.org
Wed Dec 7 22:49:54 CET 2011


New submission from Matt Long <matt at crocodoc.com>:

The description of nesting list comprehensions in section 5.1.5 of the main Python tutorial (http://docs.python.org/tutorial/datastructures.html#nested-list-comprehensions) is misleading at best and arguably incorrect. Where it says "To avoid apprehension when nesting list comprehensions, read from right to left." This is incorrect and conflicts directly with the comment at the bottom of PEP 202 (http://www.python.org/dev/peps/pep-0202/), which says the last index varies fastest.

Take the following example:

matrix = [[1,2],[3,4],[5,6]]
my_list = []
for row in matrix:
  for number in row
    my_list.append(number)

The current documentation would suggest I do the following to achieve the same result with list comprehensions since the for statements should be read from right to left:

matrix = [[1,2],[3,4],[5,6]]
my_list = [number for number in row for row in matrix]

Running this code will result in an error. The correct form is:

matrix = [[1,2],[3,4],[5,6]]
[number for row in matrix for number in row]

Clearly the nesting order only matters when the inner loop depends on the outer loop as in my example above. There is no such dependency in the documentation's example, which is why it is does not result in an Error.

----------
assignee: docs at python
components: Documentation
messages: 148994
nosy: docs at python, mattlong
priority: normal
severity: normal
status: open
title: Incorrect nested list comprehension documentation
type: behavior
versions: Python 2.6, Python 2.7

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue13549>
_______________________________________


More information about the New-bugs-announce mailing list