python – How to change values ​​in a list without creating a new list?

Question:

The standard way is via list list comprehension :

my_list=[1,2,3,4,5,6]
my_list_1=[i*5 for i in my_list]
print(my_list_1)

Why can't I do the same with the original list:

my_list=[1,2,3,4,5,6]
for i in my_list:
    i*=5
print(my_list)

This code doesn't work, why?

Answer:

For this design:

for i in my_list:
    i*=5

Python creates a new variable i which contains the values ​​from the list in sequence. As a result, you change the values ​​of the variable i , the list remains unchanged.

In [136]: my_list=[1,2,3,4,5,6]
     ...: for i in my_list:
     ...:     i*=5
     ...:     print(i, my_list)
     ...:
5 [1, 2, 3, 4, 5, 6]
10 [1, 2, 3, 4, 5, 6]
15 [1, 2, 3, 4, 5, 6]
20 [1, 2, 3, 4, 5, 6]
25 [1, 2, 3, 4, 5, 6]
30 [1, 2, 3, 4, 5, 6]

In the following line of code, you assign the result of a list comprehension to my_list_1 :

my_list_1=[i*5 for i in my_list]

Solution:

my_list[:] = [i*5 for i in my_list]
print(my_list)
#[5, 10, 15, 20, 25, 30]

PS You can read more about assignments to lists and slices in the answers to this question in the English version of SO

Scroll to Top