stretching list comprehensions

Delaney, Timothy C (Timothy) tdelaney at
Tue Aug 12 01:43:36 CEST 2003

> From: Simon Burton [mailto:simonb at]
> >>> 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
> >>> 

That is exactly equivalent to:

nums = []

for x in range(y):
    for y in range(10):
        nums.append(x + y)

I'll leave it to you to work out the required modification to make the above list comprehension work.

As a rule of thumb - keep list comprehensions very simple. Otherwise they become incomprehensible ...

Tim Delaney

More information about the Python-list mailing list