Loop in list.
Fredrik Lundh
fredrik at pythonware.com
Tue Feb 8 16:59:26 EST 2005
Stephen Thorne wrote:
>> '>>> a = [i*2*b for i in range(3) for b in range(4)]
>> '>>> a
>> [0, 0, 0, 0, 0, 2, 4, 6, 0, 4, 8, 12]
>>
>> Might take you a while to correlate the answer with the loop, but you
>> should be able to see after a while that this nesting is the same as
>>
>> '>>> a = []
>> '>>> for b in range(4):
>> '>>> for i in range(3):
>> '>>> a.append(i*2*b)
>
> There is a subtle error in this explanation.
if you run the example, you'll notice that it's not so subtle. read on.
> The equivilence actually looks like:
>
> '> a = []
> '> l1 = range(4)
> '> l2 = range(3)
> '> for b in l1:
> '> for i in l2:
> '> a.append(i*2*b)
really?
def myrange(x):
print "RANGE", x
return range(x)
print [i*2*b for i in myrange(3) for b in myrange(4)]
a = []
for b in myrange(4):
for i in myrange(3):
a.append(i*2*b)
print a
a = []
l1 = myrange(4)
l2 = myrange(3)
for b in l1:
for i in l2:
a.append(i*2*b)
print a
prints
RANGE 3
RANGE 4
RANGE 4
RANGE 4
[0, 0, 0, 0, 0, 2, 4, 6, 0, 4, 8, 12]
RANGE 4
RANGE 3
RANGE 3
RANGE 3
RANGE 3
[0, 0, 0, 0, 2, 4, 0, 4, 8, 0, 6, 12]
RANGE 4
RANGE 3
[0, 0, 0, 0, 2, 4, 0, 4, 8, 0, 6, 12]
(to translate a list comprehension to nested statements, remove
the result expression, insert colons and newlines between the for/if
statement parts, and put the append(result expression) part inside
the innermost statement)
</F>
More information about the Python-list
mailing list