Loop in list.

Stephen Thorne stephen.thorne at gmail.com
Tue Feb 8 16:07:55 EST 2005


On Tue, 08 Feb 2005 23:07:09 -0500, Caleb Hattingh <caleb1 at telkomsa.net> 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. 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)

Stephen



More information about the Python-list mailing list