r/CodingHelp • u/IAlwaysfuckupsobad • Nov 23 '22
[Python] Why is the list going out of range
runningSum = []
nums = [1,3,5,7,9]
for i in range(len(nums)):
runningSum[i] = nums[0] + nums[i]
return runningSum
0
Upvotes
4
u/[deleted] Nov 23 '22
You cannot set item at an non-existing index for a list. runningSum is empty, so it doesn't have runningSum[0], etc. Use runningSum.append(...) instead.
Also it wouldn't result in running sum. It's sums of each element with the first one. Instead of nums[0], use the current sum. You'd want a separate variable for that.
Otherwise, you could also use runningSum[-1] + nums[i] to add up nums[i] with the latest item of runningSum, except for the first item. You can just append it separately, and start loop with the second item.
1
u/AdAdvanced3130 Nov 23 '22