Hi! I am new to coding and was trying to solve I tried to solve a problem that required me to sum all of the negative integers in a list using loops. I tried to solve the problem using both for and while loops but got different answers.
For Loop Code
glist3 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
total3=0
for i in glist3:
if glist3[i]<0:
total3+=glist3[i]
print(total3)
While Loop Code
glist4 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
i2=0
total4=0
while i2 < len(glist4):
if glist4[i2] < 0:
total4+=glist4[i2]
i2+=1
print (total4)
The Result I got for the for loop is -12 (which is incorrect), but the while loop did give back the correct answer which is -13. Just wanted to ask for possible causes for this discrepancy. Thank you!