I have reviewed a number of topics on mutation and list mutation and yet, I have encountered an example that none of what I have been able to find resolves. Specifically, I was experimenting with nested indexing, so I built the kind of convoluted list object that probably would be "bad practice" in the real world. But just for the learning, I wanted to create index examples and decided to test it for mutation as well. This object mutates when you try to copy it (see code below). Among the things I tried to get around this that failed were as follows:
Python documentation describes copy() and deepcopy() but it turns out these methods do not exist on list (at least that is the error I get).
x2 = x[:] is supposed to solve the problem through slicing. This too does not work on the object given below (it still mutates)
list2 = list(list1) - this works on simple lists, but not the crazy mixed object storage list given below
How would I copy something like this and not have it mutate?
I do not expect to ever create something like this for real, but smaller mixed object lists that have the same symptoms probably do have valid use cases in real code. Anyone who can crack this, it would be appreciated ...
This code was in a Jupyter notebook running Python 2.7:
import numpy as np
import pandas as pd
m3d=np.random.rand(3,4,5)
n3d=m3d.reshape(4,3,5)
o3d=np.random.rand(2,3,4,5)
# some simple arrays:
simp1=np.array([[1,2,3,4,5]])
simp2=np.array([[10,9,8,7,6]])
simp3=[11,12,13]
# a dictionary
dfrm1 = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],
'year': [2000, 2001, 2002, 2001, 2002],
'population': [1.5, 1.7, 3.6, 2.4, 2.9]}
# convert dictionary to DataFrame
dfrm1 = pd.DataFrame(dfrm1)
trueSimp1=np.array([10,9,8,7,6])
crazyList = [simp1, m3d, simp2, n3d, simp3, dfrm1, o3d, trueSimp1]
Now how do we create crazyList2 so it does not mutate after creating the copy?
Failed attempts included:
crazyList2 = list(crazyList)
crazyList3 = crazyList[:]
crazyList4 = crazyList[:-1]
crazyList4 = crazyList4.append(crazyList[7]) # 7 is last object in list
To test this ... some good elements to change in each list and see if they effect the others:
crazyList3[7][1] = 13 # change value here in any one list and check the others
crazyList3[4][0] = 14 # change value here in any one list and check the others
In my tests, they always did ... proving mutation despite the different ways I attempted to get around it.