Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply every element of a list by a number

Tags:

python

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)
like image 981
AdR Avatar asked Feb 12 '16 05:02

AdR


2 Answers

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.

like image 97
Remi Crystal Avatar answered Sep 18 '22 14:09

Remi Crystal


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
like image 22
Selcuk Avatar answered Sep 16 '22 14:09

Selcuk