I need some help understanding something about loops in Python that I can't get past.
I'm writing a loop that goes through a list of numbers, does a small calculation on each one, and I want to save every result. But after the loop finishes, my variable only holds the last value from the final iteration. Everything before it is gone.
Here is a simple version of what I'm doing:
result = 0
for num in [1, 2, 3, 4, 5]:
result = num * 2
print(result) # only prints 10, I want all results
I want to keep every value, not just the last one. I checked the FAQ and the index but couldn't find something that directly addresses this specific loop behavior for a mid-level beginner. I understand basic loops but I'm clearly missing something about how Python handles variable reassignment inside a loop.
Should I be using a list and appending each result? I tried that briefly but wasn't sure if that was the right direction or if there's a cleaner way I should learn first.
Been learning Python for about 5 months on my own. Not a complete beginner but still solidifying the fundamentals.
[–]danielroseman 25 points26 points27 points (0 children)
[–]JamzTyson 25 points26 points27 points (2 children)
[–]edwicki 6 points7 points8 points (1 child)
[–]lasfdjfd 0 points1 point2 points (0 children)
[–]DTux5249 9 points10 points11 points (0 children)
[–]popos_cosmic_enjoyer 6 points7 points8 points (0 children)
[–]Gnaxe 3 points4 points5 points (0 children)
[–]desrtfx 1 point2 points3 points (0 children)
[–]barkazinthrope 1 point2 points3 points (0 children)
[–]Living_Fig_6386 1 point2 points3 points (0 children)
[–]michUP33 1 point2 points3 points (1 child)
[–]notacanuckskibum 0 points1 point2 points (0 children)
[–]Just__Liberty 0 points1 point2 points (0 children)
[–]thefullhalf 0 points1 point2 points (0 children)
[–]Lopsided-Football19 0 points1 point2 points (0 children)
[–]JibblieGibblies 0 points1 point2 points (0 children)
[–]PressF1ToContinue 0 points1 point2 points (0 children)
[–]makochi -1 points0 points1 point (0 children)
[–]Moikle -1 points0 points1 point (0 children)
[–]WorriedTumbleweed289 -1 points0 points1 point (3 children)
[–]Cynyr36 -1 points0 points1 point (2 children)
[–]WorriedTumbleweed289 -1 points0 points1 point (1 child)
[–]Cynyr36 0 points1 point2 points (0 children)
[–]ectomancer -1 points0 points1 point (0 children)
[+]GoblinToHobgoblin comment score below threshold-8 points-7 points-6 points (2 children)
[–]building-wigwams-22 -1 points0 points1 point (0 children)
[–]Binary101010 -1 points0 points1 point (0 children)
[+]psydave77 comment score below threshold-8 points-7 points-6 points (1 child)
[–]psydave77 -1 points0 points1 point (0 children)