list comprehensions

Terry Reedy tjreedy at udel.edu
Thu Apr 8 09:51:08 EDT 2004


"Elaine Jackson" <elainejackson7355 at home.com> wrote in message
news:i56dc.46224$Pk3.1562 at pd7tw1no...
> But I stand by my complaint about unintuitiveness,

Which I already agreed with, which I why I said, "Don't try to intuit!";-)

> because I've discovered that you get an error from
>
> x = [(i,j) for i in range(7-j) for j in range(3)]

because the i loop is outside/before the j loop.  The problem with trying
to intuit is that list comps move the appended expression from inside to
outtermost while otherwise leaving the order outside-in.  You were
expecting the order to be uniformly reversed, and it is not.  If the syntax
had specified the above to be written as

[for i in range(7-j): for j in range(3): (i,j)]

which more obviously abbreviates the corresponding statements, the error
would be more obvious.  Moving the expression to the front was, of course,
intentional -- to make it stand out more -- but I can be somewhat confusing
at first until one gets used to it.

 > while
>
> y = [[(i,j) for i in range(7-j)] for j in range(3)]
>
> works fine.

because now the i-loop, as part of the appended expression, gets executed
inside the j loop.

y=[]
for j in range(3):
  y.append([(i,j) for i in range(7-j)])

Terry J. Reedy







More information about the Python-list mailing list