For loop lists - calculating total/sum

Hi this is a simple question asked out of curiosity.

I am wondering why the formula used below does not factor in the exact values in the original list. The total calculated is 45, when it should be 42. I ended up using range(len()) to rectify this. But when checking as to what caused this, I see that print(list[a]) returns a few different numbers.

The output has an additional 4 and 5, but does not have the number 3 as in the original list.

list = [0, 9, 5, 4, 8, 2, 3, 0, 1, 5, 3, 2]

total = 0
for a in list:
total += list[a]
print(list[a])
print(total)

Output =
0
5
2
8
1
5
4
0
9
2
4
5
total = 45

Hello @Astra0508 , welcome to the community!

when you use for a in list, the a is already the value inside the list, not the index. Because of this, you don’t need to use list[a] to access the value.

What you’re trying to do, can be done like this:

total = 0
for a in list:
    total += a
    print(a)

Now explaining your output:

In your for loop, the a will represent each value in the list in each iteration. As the first value in the list is 0, in the first iteration, a is equal to 0. Therefore, when you do list[a], you’re doing list[0], which means you’re accessing the index 0 of the list, which is 0 itself. That’s the first output you have.

When the for loop moves on to the next iteration, a becomes 9 and therefore list[a] is equals to list[9], which means you’re accessing the element of index 9 in your list. That element is 5, which is your second output.

An so on…


Also, it’s not a great practice to name a list as list in python, because this is already the name of the function list(), used to create lists.

Hope this is helpful.

2 Likes

Thanks for the detailed explanation Otavios! This turned on some lightbulbs for me.

1 Like