stretching list comprehensions

David Eppstein eppstein at ics.uci.edu
Tue Aug 12 01:44:52 CEST 2003


In article <pan.2003.08.11.23.26.39.60449 at webone.com.au>,
 Simon Burton <simonb at webone.com.au> wrote:

> >>> del y
> >>> nums = [ x+y for x in range(y) for y in range(10) ]
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> NameError: name 'y' is not defined
> >>> 
> 
> Well.. Is there an inherent reason why this could/should not be made to work?
> 

It does work with the loops in the opposite order:

>>> [x+y for x in range(10) for y in range(x)]
[1, 2, 3, 3, 4, 5, 4, 5, 6, 7, 5, 6, 7, 8, 9, 6, 7, 8, 9, 10, 11, 7, 8, 
9, 10, 11, 12, 13, 8, 9, 10, 11, 12, 13, 14, 15, 9, 10, 11, 12, 13, 14, 
15, 16, 17]

The way you wrote it doesn't work for similar reasons to why it doesn't 
work to do
    for x in range(y):
        for y in range(10):
            print x+y
The variable y is not defined in time to use it.

-- 
David Eppstein                      http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science




More information about the Python-list mailing list