Can you help me with an exercise please?


I’m facing problems with task No. 4 and I find it still too early to check for the solution. This is my code so far:

single_digits = list(range(10))
for each in single_digits:
squares =
squares.append(each ** 2)

It wants me to append the squared value of each element of single_digits to the list squares, but it seems that I got only the last element appended. Why is that happening? I think it might be connected to the codeline - print(each) - having printed all the numbers but not all in one row but 1 by 1 in 10 rows. I tried to change its indentation but didn’t help.

Thank you.

its because you “define” the squares variable inside the loop, so each iteration of the loop, a new empty list is created, a value is added, then the loop goes to the next iteration, an empty list is created again, a single value is added/appended, and so forth until you end up with the last value


Thank you very much sir, now it works!

I’ll reread your message though in order to try to grasp the theory of my variable being defined inside the loop.

Have a nice day.

you have a loop:

for each in single_digits:
   # code to be executed in the loop

then in the loop you have the body of the loop, code to run during the iterations of the loop. By placing squares = [] in the loop body, this statement is executed each iteration of the loop

the normal flow would be to have the list first, followed by the loop to append items to the list