I would like to multiply all elements of a list by a number. I know the other ways to do it but I want to know Why isn't this working? I am getting the very same list as an output.
lst = eval(input('enter a list'))
for num in lst:
num = num * 2
print(lst)
It isn't working because, you're using for
loop on a list and defining/changing the num
global variable, not the elements in lst
list.
For example:
>>> l = [1, 5, 8]
>>> for num in l:
... num *= 2
...
...
>>> num
16
>>> l
[1, 5, 8]
In this case, in the first loop, num
is 1
(the first element in l
), and sure 1 * 2
gives 2
.
Then, num
become 5
since 5
is the second element in the list. After num * 2
, num
become 10
.
In the second for
loop, it become 8 * 2
, 16
. it doesn't change again because the for
loop is ended.
However, you didn't change anything of the list during this loop. Because for
only gets the elements in the list, and put it into a temporary variable.
And when you change that temporary variable inside the for
loop, you didn't change anything of the list.
Well, since you wrote "I know the other ways to do it but I want to know Why isn't this working?", here is your answer: You are only modifying the temporary loop variable num
, not the list itself. Try this:
for i, num in enumerate(lst):
lst[i] = lst[i] * 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With