Python for loop

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)

I do not understand why the answer below is correct.

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

When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!

If you want to have the best chances of getting a useful answer quickly, make sure you follow our guidelines about how to ask a good question. That way you’ll be helping everyone – helping people to answer your question and helping others who are stuck to find the question and answer! :slight_smile:

Write it out by hand to see the change.

For example (this is not code, it’d be by hand):

first iteration:
old = 0
i = 0
list2.append(0) #0+0
(list2=0)

2nd iteration:
old = 0
i = 1
list2.append(1) #0+1
(list=[0,1])

3rd iteration:
old=1
i=2
list2.append(3) #1+2
(list=[0,1,3])
2 Likes

How did you know when old = 1 in the third iteration?

https://www.codecademy.com/paths/computer-science/tracks/cspath-flow-data-iteration/modules/dspath-python-loops/lessons/python-functions-loops-cc/exercises/divisible-by-ten

Can you explain why we equal to zero in the if statement?

Each time the for loop iterates, old is assigned the value of i. The first time the loop iterates, i = 0 (the first element in list1) and old = 0 as defined in the first line, so the value of 0 + 0 is appended. Then, we assign old the value of i, which was 0 since it is still the first iteration of the loop.

The second time the loop iterates i = 1 and old = 0, so the value of 1 + 0 is appended. Then, we once again assign old the value of i, where now i = 1 (the second element in list1).

At this point, old = 1. The third time the loop iterates, i = 2 and old = 1 so the value of 2 + 1 is appended. This continues until the last element of list1 has been iterated over.

1 Like

I presume you are referring to the following line.

if i % 10 == 0:

The modulo operator returns the remainder of one number divided by another. In this case, it returns the remainder of i divided by 10. If a number is divisible by 10, it should have no remainder.

30 / 10 == 3       ->       # is divisible by 10 (remainder is 0)
22 / 10 = 2.2      ->       # is not divisible by 10 (remainder is 2)

Since we are trying to find out if a certain number is divisible by 10, and numbers that are divisible by 10 have a remainder of 0 when divided by 10, we can use an if statement to check if a number modulo 10 is equal to 0.

2 Likes

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.