Loop in list.

Caleb Hattingh caleb1 at telkomsa.net
Tue Feb 8 23:07:09 EST 2005


Jim

Someone on this list (SteveB) helped me quite a bit with a list  
comprehension on a recent thread.  Roy said it can be hard to read, and I  
agree in part because I always thought they were hard to read, when in  
actual fact I had just never bothered to learn properly.  Here is a  
mini-tutorial:

e.g. 1: The theory

'>>> a = [ <item1> for i in <item2> ]

item2 is iterable (like "range()" in your example)
item1 is the thing that is going to fill up the resulting list, and item1  
is evaluated at each step of the "for" loop.

This is the same as
'>>> a = []
'>>> for i in <item2>:
'>>>     a.append(<item1>)

e.g. 2: A real example

'>>> a = [i*2 for i in range(3)]
'>>> a
[0, 2, 4]

so "i*2" gets evaluated for each step in the "for" loop.  The values of  
"i" at each step are [0,1,2], according to how "range" works, so "i*2" is  
what you end up with in the resulting list.

e.g. 3: They can be nested

'>>> 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)

keep well
Caleb





More information about the Python-list mailing list