Search code examples
pythonarrayscloning

What does List[:][:] really do in Python?


I tried to make a copy of a 2 dimensional array using the splicing operator. Intuitivelly, it feels like if I do this:

L = [[5, 6], [7, 8]] 
M = L[:][:] 

then M would be a cloned copy of every nested element in L. So I could change items in M[0] without changing L:

M[1] = [3, 4] 
M[0][1] = 2 

But when I do this:

print(L)
#returns [[5,2],[7,8]]

What is actually going on in Python's memory when I performed the [:][:] operation?


Solution

  • Just makes a copy of the list on the left side of the operator [:].

    [:][:] does copy of copy. You can do M = L[:][:][:][:][:][:][:][:][:][:][:][:][:][:] and it works the same way :D

    To make a copy of nested lists as well you should do it like M = [x[:] for x in L[:]]

    Then M would be a cloned copy of every nested element in L. It is not true because L[:][:] is the same as (L[:])[:] it is a copy of the copy of the original list.

    M[1] = [3, 4] here you modify the second item of the COPY.

    But here M[0][1] = 2 you are modifying an item of the original nested array since [:] doesn't do any copy operations on nested lists and the copied original list item was not "simple".