1

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

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
Simon
  • 9,762
  • 15
  • 62
  • 119
  • _"As far as I know, there is no link between the abPositions and abPositionsRotated"_ Just because you made a copy of the _outer list_, doesn't mean you made a copy of the _inner_ list. `abPositionsRotated[0]` and `abPositions[0]` are the same object. – Burhan Khalid Aug 01 '14 at 07:48
  • 1
    See e.g. [here](http://stackoverflow.com/q/25035664/3001761) - `list(...)` is also a **shallow copy**. – jonrsharpe Aug 01 '14 at 07:51

1 Answers1

1

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.

Yuushi
  • 25,132
  • 7
  • 63
  • 81