list comprehensions whats happening here

Carlos Ribeiro cribeiro at mail.inet.com.br
Fri Apr 13 13:28:24 EDT 2001


At 07:06 13/04/01 -0700, Emile van Sebille wrote:
>I suspect the answer lies somewhere in the comma converting the parts of the
>list comprehension into a list itself, much as the comma is used in normal
>iteration idiom:
>
>for i in 1,2

As other have pointed out, your're right, that does explain why it works 
that way. But...

 >>>[[i,j] [1,2,3], for j in 'abc',]
Traceback (  File "<interactive input>", line 1
     [[i,j] [1,2,3], for j in 'abc',]

does not work, yet

 >>> [[i,j] for i in range(3), for j in range(3)]
[[[0, 1, 2], 0], [[0, 1, 2], 1], [[0, 1, 2], 2]]

work.

I am not advocating that something is wrong; I just want to point out that 
some funny things are happening as a side effect of the grammar and/or 
compiler. It's impossible to supply a list as part of the list 
comprehension syntax, but you can fake it by writing a comma after the for 
clause. That's just weird, and unexpected.

Question: this may turn out to be wrong, and it may be fixed in the future; 
OTOH, it can be useful, and (in a rather obscure way) consistent with 
Python syntax. What's the take on this? Let it be, or fix it, as a 
undesirable side effect that don't belong to list comprehensions?


Carlos Ribeiro






More information about the Python-list mailing list