My brain isn't making sense of codes lately

I have been confused on some of the topics so I decided to work on practice packs to see if it would help me…
I’m having little luck. I’m at a place where I don’t really understand how things go together for some reason… not sure I’m making sense…

I took a quiz on the lists practice pack and the answer is below… I cannot wrap my mind around how the code yields such a result. I simply can’t. Can anyone break this down for me?

old = 0
list1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list2=
for i in list1:
list2.append( i + old)
old = i
print(list2)

OUTPUT BELOW

[0, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

JUST HOW??

It has to do with the old variable. Each iteration, after the append(old+i) calculation, old is set to i. So:
When i is 0, old is 0. Therefore, 0+0=0.
When i is 1, old is still 0. Therefore, 1+0=1
When i is 2, old is 1. Therefore, 2+1=3.
When i is 3, old is 2. Therefore, 2+3=5.
And this repeats.


Basically, because the calculation is happening before old is set to a value, it skips even numbers (except for zero) up to 9+10 giving 19.
I hope this helps!

4 Likes

Thank you for your help!
Last question regarding the code:
When you say that because it’s set before old has a value therefore it skips even numbers, what part of the code tells me this?

I have been struggling to work through longer codes because I don’t seem to be able to break things down effectively.

Is there a tutor or something that can be recommended for people like me?

I really appreciate it!!

I’m sure you can get tutors where you live or online, but I don’t really know…

When I see the code, I immediately look for what’s happening inside the loop. Northing unusual, no logic (if, etc). Ok. Ah, but there’s something inside the loop referencing something outside of the loop, which means something weird might be happening. Then, I just ran the code, and added a few print statements inside the loop to see what was going on.