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)
Answer: [0]
Code 2:
my_list = [0,1,2,3]
x = 1
for elem in my_list:
new_list = x * elem
print (new_list)
Answer: [3]
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)
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:
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!