newbie question
Wayne Brehaut
wbrehaut at mcsnet.ca
Fri Apr 1 16:55:34 EDT 2011
On Fri, 1 Apr 2011 21:52:24 +0200, 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--to see what 'j' is, comment out your "sum = sum + bList[j]"
statement and run again.
The name 'j' refers in order to the 0th, 1st, etc., value in bList,
and it's therefore just 'j' (i.e., the value that j now refers to) you
want to add to the sum.
To get "the usual" (in many oter PLs) indexing instead you would use:
for j in range(len(bList)):
sum = sum + bList[j]
And if you again comment out the "sum =..." and add:
print j, bList[j]
you'll see the difference.
wwwayne
>
>Thanks!
>
>Karl
More information about the Python-list
mailing list