1

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:

  1. 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).

  2. x2 = x[:] is supposed to solve the problem through slicing. This too does not work on the object given below (it still mutates)

  3. 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.

TMWP
  • 1,545
  • 1
  • 17
  • 31
  • You are doing _shallow_ copy and your list contains mutable elements. You need a `deepcopy`. – Łukasz Rogalski Feb 23 '17 at 16:31
  • You're supposed to `import copy` and call `copy.deepcopy(list)` Lists don't have a `copy` or `deepcopy` method (in python2) – danidee Feb 23 '17 at 16:34
  • thanks for these posts. Why this online documentation does not start with the library you need to import to copy/deepcopy is beyond me. :-) https://docs.python.org/2/library/copy.html – TMWP Feb 23 '17 at 17:15
  • @danidee - having a problem on this site right now. Seems people answer my posts in comments and even spend time adding helpful edits to them but no upvotes or posted answers. This results in the zeroes on these questions averaging in in such a way that I am getting a warning that I may not be able to ask questions here soon. I am new and just looking to both contribute and get help from the community. Were you aware the system worked this way when you left the question at zero and answerd in a comment rather than a post? – TMWP Mar 14 '17 at 13:12
  • 1
    Hello @TMWP They're five major reasons why people leave comments on a question (at least for me) 1.The question is a duplicate, so they just drop hints to guide you, 2.Your problem/Question is caused by something that's not reproducible (Typo mostly) 3.They don't feel their answer should be posted as an answer because it's too short (or they're similar questions that it would make no sense to post a new answer...Relates to no. 1) 4.They need clarification 5.They're not sure of the answer but feel they can chip in something to help. – danidee Mar 16 '17 at 11:52
  • 1
    Stackoverflow isn't all about rep (Though it feels good to see your rep growing) but at the end of the day the reps are just internet points sitting in a database somewhere that can easily be erased if there's an apocalypse :D. My point is there's so much more to gain from Stackoverflow than reputation so i'll beg you not to get discouraged and keep on participating (answering and asking). My first question a few years ago was "How can i build a music streaming site with PHP". I got about 7 downvotes in 2 minutes and i was banned from asking a question until i answered to overturn the deficit. – danidee Mar 16 '17 at 11:57
  • There are so many users with unfair reputation on Stackoverflow (Most of which was gotten when the site was still young). but Today things are different, people don't upvote questions (and answers) as much as they use to. So if you really want your rep to grow faster, Your best bet is to answer more questions. Here is an example of a question where a lot of unfair rep was gained http://stackoverflow.com/questions/1024847/add-key-to-a-dictionary-in-python way back in 2009. You can't really call it unfair because well....There were there before you :). I still hope you see you around Cheers! – danidee Mar 16 '17 at 12:04
  • Thanks for your answer. You may be interested by a few things i learned doing similar posts on other questions. Several people admitted they were commenting instead of answering for fear of having their answer downvoted (they had gotten bitten before). In my case, people liked the question enough to drill into it with helpful suggestions and even to edit the content to make it look nicer or for nit-picky grammar and style concerns sometimes genuinely enhancing readability and sometimes not, and yet after spending all that time on my question, still no up-vote, or posted answer ... – TMWP Mar 16 '17 at 20:28
  • I believe I have managed to address my deficit now, but doing it through answering more questions is risky because of down-voters. While this site is "not about rep", various abilities to use the site and participate on it are awarded and/or taken away by how many rep points you have. If you fall below margin you lose priveleges. By building up your numbers you gain them. If I ever get like the experienced people on here with a massive cushion, I may not care so much but right now, I am still building up the ability to fully participate. Among actions I took to fix the deficit ... – TMWP Mar 16 '17 at 20:32

0 Answers0