On 04/01/2011 12:52 PM, Karl 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]
Your j is already an element of bList. You don't need to index bList
again. Instead do
for b in bList:
sum = sum+b
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, it's not a control variable, it's the actual elements of the list.
If you want a control variable as an index you can do
for j in range(len(bList)):
sum = sum + bList[j]
But that is less efficient
Thanks!
Karl
--
http://mail.python.org/mailman/listinfo/python-list