# For Loop in Python

Pardon if I have been posting series of questions. Newbie Python learner here, and am going through PCEP materials, and having some questions along the way… Thank you in advance for the help.

In these two codes, I confused why the answer is such:

Code 1:

``````my_list = [0,1,2,3]
x = 1
for elem in my_list:
x *= elem
print (x)
``````

Code 2:

``````my_list = [0,1,2,3]
x = 1
for elem in my_list:
new_list = x * elem
print (new_list)
``````

Question 3: I want to create a code that multiplies all elements in the list by x. For example, x=2 in this case. But I am encountering an error with my code… How do I correct this? Thanks!

``````my_list = [0,1,2,3]
new_list=[ ]
x = 2
for elem in my_list:
new_list.append= x*elem
print (new_list)
``````

Well, what is `1 x 0 x 1 x 2 x 3`?

1 Like

x and elem are both integers, so x * elem is also an integer. You’ve assigned the result to a variable called `new_list`, but it’s not a list. Each time through the loop, the previously assigned value is discarded. When you exit the loop, only the final multiplication remains.
(And you mention the output is `[3]`, but it is instead `3`, so an integer, not a list)

You don’t assign to the .append method, you call it with an argument. So this should be instead:

``````for elem in my list:
new_list.append(x*elem)
``````
1 Like
``````# Change this
new_list.append= x*elem

# To this
new_list.append(x * elem)
``````

List comprehension version:

``````my_list = [0, 1, 2, 3]
x = 2
new_list = [i * x for i in my_list]
print (new_list)
``````
1 Like

Oh, x it is to be multiplied to all elements. I see. I thought it is x multiplied to each of the elements, producing the same list values [0,1,2,3]. Thanks for the explanation!

Thank you so much for the explanation and correction. It is much clearer now.

Thank you!