# Nested list comprehensions

Carl Waldbieser waldbie at yahoo.com
Sun Nov 27 04:49:07 CET 2005

neildunn at gmail.com wrote:

> 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
You may not be getting the name error in the interpreter because you already
defined those variables.  Try this:

\$ python
>>> [(j,k) for j in range(1,k) for k in range(1,5)]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'k' is not defined
>>>

Looks like the variable was not defined here, either.

You are trying to use the variable "k" in the range() function before it has
been bound to anything, hence the error.

More information about the Python-list mailing list