Learning Python for the first time! need help For loop?

Hi all,

I appreciate your help; I am learning Python from scratch coming from a totally different field. In the first course in the data science in python, can someone please explain how did we get the answer for this code what is happening at the background level?

a_list = [1,2,3]

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

The answer is:
1
0
2
1
3
2

How did we get this answer?

Thank you so much.

Hi @jehan.lina

Let’s understand how this code works.

a_list = [1, 2, 3]    # defined a list
for value in a_list:  # iterate through each element of a_list
     print(value)     # print each element of list
     print(value-1)   # print each element after subtracting 1 from it.

First iteration value = 1 from a_list, So output is 1 then (1-1) i.e. 0. Same in second iteration value = 2, So output is 2 then (2-1) i.e. 1.

# So final output of code is
1    # value   first iteration
0    # value-1
2    # value  second iteration
1    # value-1
3    # value third iteration
2    # value-1

I hope this helps :slightly_smiling_face: .

2 Likes

Thank you so much; It did indeed help me to understand it.

2 Likes