stretching list comprehensions

Delaney, Timothy C (Timothy) tdelaney at avaya.com
Mon Aug 11 19:43:36 EDT 2003


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