Home > Software design >  Python Copy Behaviour on Sliced Nested Lists
Python Copy Behaviour on Sliced Nested Lists

Time:09-17

I do not understand the copy behaviour for nested lists in Python when slicing. I know that I can use copy.deepcopy() if I want to clone everything, but I'm asking more about the design of the language here, rather than solving a problem.

This makes sense, because each element is copied during slicing:

foo = [0, 0, 0]
bar = foo[:]
bar[0] = -1
print(foo) # [0, 0, 0]

This also makes sense, because slicing the zeroth index creates a new list, filled with references to foo's sub-lists (similar to a shallow copy):

foo = [[0], [0], [0]]
bar = foo[:]
bar[0][0] = -1
print(foo) # [[-1], [0], [0]]

This however does not follow from the pattern above:

foo = [[0], [0], [0]]
bar = foo[:][:]
bar[0][0] = -1
print(foo) # [[-1], [0], [0]]

In the example above, I would have expected the output [[0], [0], [0]] because I have sliced both axes, and so expected that elements in the sub-lists would have been copied as well. I found a similar observation with numpy arrays.

I was wondering why is it like this?

CodePudding user response:

In the second and third example your foo is 2d array you need write [foo[:]][:] like below:

foo = [[0], [0], [0]]
bar = [foo[:]][:]
bar[0][0] = -1
print(foo) # [[0], [0], [0]]

CodePudding user response:

I have sliced both axes

No you have not. You have sliced the first axis twice. Made a copy of a copy. No difference to just a copy.

  • Related