So, there's two misconceptions here.
First, that loop isn't doing what you describe. Provided that sum is defined outside of it, the only values you are adding that will stick after the loop is the last element in the list and whatever is in the first position of the list. For your current list, the sum would be 7.
Second, there's a handy function to do this already - sum - which would make short work of your task.
sum([4,5,65,94,3])
But if you insist on doing this yourself, you have to set up a few things:
- Ensure the variable you're accumulating to is a sentinel value for your math operation. For addition, it has to start at 0. For multiplication, it starts at 1.
- Add to your original value; don't overwrite its value. This would mean either
total = total + i or total += i.
- Remember that Python's
for loop is actually a for-each loop. i will advance through your list and be bound to each value in turn.
To fix the code, you'd want to do this:
total = 0
li = [4,5,65,94,3]
for i in li:
total += i
As a final note, avoid shadowing function names. list and sum are already defined as functions, and you really don't want to go shadowing them.
list[0]withlist[var2]sum * number of items?sumis actually just the some of the last element with the first element. Is that what you expect?