0

Very simple python, I just create a new list object by copying the old list. By using .copy() method, I thought it should create a new object in Python based on the official doc: https://docs.python.org/3.6/library/stdtypes.html?highlight=list#list
How come after I update the elements in the new object, the elements in the old list object also got changed.

old =  [[1, 1, 1],
        [1, 1, 1],
        [1, 1, 1],
        [1, 1, 1]]

print(old)
new = old.copy()
for i in range(len(new)):
    for j in range(len(new[0])):
        new[i][j] = 0
print(old)
print(new)

How come the output is, where I expect the old value shouldn't be changed:

[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
Andrew Brēza
  • 7,705
  • 3
  • 34
  • 40
Patrick
  • 797
  • 5
  • 15
  • `list.copy` does a shallow copy, so if the outer list contains lists, the new list will still refer to the old inner lists. If you don't want to import `deepcopy` you can do this to create copies of the inner lists: `new = [u[:] for u in old]`. – PM 2Ring Jul 21 '17 at 06:26

2 Answers2

6

Copy only works with one dimension lists. For a better solution that works regardless of the number of dimensions use deepcopy:

from copy import deepcopy

old =  [[1, 1, 1],
        [1, 1, 1],
        [1, 1, 1],
        [1, 1, 1]]

print(old)
new = deepcopy(old)
for i in range(len(new)):
    for j in range(len(new[0])):
        new[i][j] = 0
print(old)
print(new)

And you will have:

[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]
[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

Hope it helps!

Jahongir Rahmonov
  • 13,083
  • 10
  • 47
  • 91
0

Try [copy.deepcopy][1] or

from copy import deepcopy
new = deepcopy(old)

from the source

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original. A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

Vishnu Upadhyay
  • 5,043
  • 1
  • 13
  • 24