How does this function work?

Robert Brewer fumanchu at amor.org
Mon Sep 20 16:05:27 EDT 2004


Jp wrote:
>   >>> def f(y):
>   ...     return [x for x in range(3), 1, y for y in range(4), 4]
>   ... 
>   >>> f(3)
>   [[0, 1, 2], [0, 1, 2], 1, 1, 3, 3]
>   >>> 
> 
>   I've been staring at it for 15 minutes and I'm no closer to 
> understanding than when I started.
> 
>   Why is this even legal Python syntax?  What is going on 
> that makes it return what it does?

A couple of parentheses might get you started. Your function is exactly
the same if you write:

>>> def g(y):
...     return [x for x in (range(3), 1, y) for y in (range(4), 4)]

>>> f.func_code.co_code == g.func_code.co_code
True

So your statement is being parsed as a single compound listcomp.
Expanding the listcomp produces:

>>> def h(y):
... 	r = []
... 	for x in (range(3), 1, y):
... 		for y in (range(4), 4):
... 			r.append(x)
... 	return r
... 
>>> h(3)
[[0, 1, 2], [0, 1, 2], 1, 1, 3, 3]

Further, (range(4), 4) evaluates to ([0, 1, 2, 3], 4); that is, a
two-item list. Since neither is referenced in the inner loop, we can
simply say the inner loop runs twice for each iteration of the outer
loop. Therefore, every value in the outer loop is doubled as you can
see.


HTH,

Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list