Search code examples
pythonlistupdating

copying a nested list, then updating values in only the new list


I have a nested list, which I make a new copy of (IDs are different). Then when I try to use indices to update a list within the new list, it ends up updating the values in both the pre and post copied lists.

I took a look at some other similar questions that talk about mutability but I'm not 100% sure I understand how it works in my specific case.

Heres some example code:

numTrials = 2

abPositions = [[1, 'a.png', [9, 9, 9, 9]], [1, 'b.png', [9, 9, 9, 9]]]

abPositionsRotated = list(abPositions)

for i in xrange(numTrials):
    abPositionsRotated[i][2] = [0,0,0,0]

print abPositions
print abPositionsRotated

so as I update the 2 sublists within abPositionsRotated, the same lists get updated in abPositions as well and I'm not sure why. As far as I know, there is no link between the abPositions and abPositionsRotated, so I dont understand why changes to one affects the other


Solution

  • Aliasing with nested lists in Python can be a bit tricky for people who aren't used to it. What you're doing is creating a separate list, but where each nested list in the separate (outer) lists points to the same memory. The solution here is simple, however: use deepcopy from the copy module:

    from copy import deepcopy
    
    abPositions = [[1, 'a.png', [9, 9, 9, 9]], [1, 'b.png', [9, 9, 9, 9]]]
    abPositionsRotated = deepcopy(abPositions)
    
    # Now any operation on abPositionsRotated will only apply to it
    

    On a completely separate note, you should probably have a read over PEP8, which is a style guide for Python.