newbie question

Ian Kelly ian.g.kelly at gmail.com
Fri Apr 1 23:00:36 CEST 2011


On Fri, Apr 1, 2011 at 1:52 PM, Karl <8213543GGXNVJXACA at kabelmail.de> wrote:
> Hello,
>
> one beginner question:
>
> aList = [0, 1, 2, 3, 4]
>
> bList = [2*i for i in aList]
>
> sum = 0
>
> for j in bList:
>
> sum = sum + bList[j]
>
>     print j
>
> 0
>
> 2
>
> 4
>
> IndexError: 'list index out of range'
>
> Why is j in the second run 2 and not 1 in the for-loop?? I think j is a
> control variable with 0, 1, 2, 3, ...

No, j is not a control variable.  It takes each value in the list in
turn.  If you really want the indexes rather than the values, do:

for j in xrange(len(bList)):
    # do something

Note that in Python 3 you should use range instead of xrange.  If you
want both the indexes and the values, then do this:

for j, value in enumerate(bList):
    # do something

Cheers,
Ian



More information about the Python-list mailing list