Blue Week Special Offer | Brighten your week!
days
hours
minutes
seconds

For loop Example doesn't make sense

I’m kind of confused. Here’s the deets.

Screen Link:
https://app.dataquest.io/c/114/m/609/for-loops-and-opening-datasets/4/for-loop-structure

My Code:

a_list = [1, 3, 5]

for value in a_list:
    print (value)
    print(value - 1)

What I expected to happen:
1
3
5
0
2
4

What actually happened:

1
0
3
2
5
4

Details:

I’m not sure if I’m not understanding how this works or not, but I expect the first iteration of the body would return the value as shown (1, 3, 5) and the second iteration would subtract one from the values shown and return (0, 2, 4)…

Thank you for any help.

1 Like

Hi @tjweaver1990 ,

Welcome to the Community!

The for-loop in your code considers only one value of the list at each iteration. So, first, it takes in 1 and performs all the operations inside the loop for that value. It means that it prints out first 1, then 0 (i.e., 1-1). Then the next iteration starts: the for-loop takes in the second value of the list (which is 3) and prints out this value and then value-1 for it (which is 2, i.e., 3-1). The same step is repeated for the third iteration, where the for-loop prints out first 5, then 4.

4 Likes

Oh wow… I completely misunderstood that part. You’re a saint.

1 Like

Please consider marking Elena’s reply as the Solution so that it can benefit others in the future as well!

2 Likes

I didn’t even think of it. Thank you

1 Like