Nested list comprehensions

neildunn at gmail.com neildunn at gmail.com
Sat Nov 26 22:00:48 EST 2005


Hey guys:

>>> [(i,j,k) for i in range(1,j) for j in range(1,k) for k in range(1,5)]
[(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 1, 4), (1, 2, 1), (1, 2, 2), (1,
2, 3), (1, 2, 4), (1, 3, 1), (1, 3, 2), (1, 3, 3), (1, 3, 4), (2, 1,
1), (2, 1, 2), (2, 1, 3), (2, 1, 4), (2, 2, 1), (2, 2, 2), (2, 2, 3),
(2, 2, 4), (2, 3, 1), (2, 3, 2), (2, 3, 3), (2, 3, 4)]
>>> def a():
...     print [(j,k) for j in range(1,k) for k in range(1,5)]
...
>>> a()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in a
UnboundLocalError: local variable 'k' referenced before assignment

Why is it that I can execute the nested list comprehension in the
intepreter
but if the same line is within a method declaration I get an unbound
reference error?

Is this a bug or am I missing some deep rule?

Regards, Neil Dunn




More information about the Python-list mailing list