stretching list comprehensions

Carl Banks imbosol at aerojockey.com
Mon Aug 11 20:04:04 EDT 2003


Simon Burton wrote:
> 
> I was quite delighted when i found this:
> 
>>>> nums = [ x+y for x in range(10) for y in range(10) ]
> 
> Great! No more list of list joining shenanigans...
> 
> Shortly thereafter, i tried this:
> 
>>>> 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?


Yes: you're doing it backwards.  Try it this way:

del x,y
nums = [ x+y for x in range(10) for y in range(x) ]


To understand why, think about the equivalent for loop:

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


If you do it the other way, you can see that y is undefined before
use.


-- 
CARL BANKS
"You don't run Microsoft Windows.  Microsoft Windows runs you."




More information about the Python-list mailing list