stretching list comprehensions

Jimmy Retzlaff jimmy at retzlaff.com
Tue Aug 12 01:47:23 CEST 2003


Simon Burton (simonb at webone.com.au):
...
> >>> 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 - y has not yet been defined when you try to start iterating over
range(y). Turn it around and it works fine:

>>> nums = [ x+y for x in range(10) for y in range(x) ]
>>> nums
[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]


Jimmy





More information about the Python-list mailing list