1

When i make a new list via copy from an existing list. The changes i made to new list also reflected in the old list. How can i solve this.

I have used .copy but it failed.

# original list
prediction = [{'seriesname': 'Male', 'data': [681, 696, 711, 726, 739]},
  {'seriesname': 'Female', 'data': [101, 104, 107, 109, 112]}]

# make a copy
prediction_percentages = prediction.copy()
# test to check the 2 objects are different
prediction_percentages is prediction
False

# Make a change in new list
prediction_percentages[0]["data"][0] = 1111

# now the changes appear in old list also 
prediction_percentages
[{'seriesname': 'Male', 'data': [1111, 696, 711, 726, 739]},
 {'seriesname': 'Female', 'data': [101, 104, 107, 109, 112]}]
prediction
[{'seriesname': 'Male', 'data': [1111, 696, 711, 726, 739]},
  {'seriesname': 'Female', 'data': [101, 104, 107, 109, 112]}]

The final result should be

prediction_percentages
[{'seriesname': 'Male', 'data': [1111, 696, 711, 726, 739]},
 {'seriesname': 'Female', 'data': [101, 104, 107, 109, 112]}]
prediction
[{'seriesname': 'Male', 'data': [681, 696, 711, 726, 739]},
  {'seriesname': 'Female', 'data': [101, 104, 107, 109, 112]}]
BlackEagle
  • 143
  • 2
  • 11

2 Answers2

3

Can use the copy module to make a deepcopy of a list:

import copy

prediction_percentages = copy.deepcopy(prediction)
kudeh
  • 883
  • 1
  • 5
  • 16
2

You're making a shallow copy of a list that contains dictionaries (mutable objects). This means that the two lists are different copies, but their elements are the same.

What you likely want is .deepcopy(): https://docs.python.org/3/library/copy.html

Christoph Burschka
  • 4,467
  • 3
  • 16
  • 31
  • Thanks for your answer but what if i use .copy for a list like `l1=[1,2]` and `l2 = l1.copy()` and `l2[0]=11`, then it would not change `l1`, so are you saying that `.copy` is useless for multi hierarchy objects. Also if i want to see the address of an object inside an object then how is `print(hex(id(prediction)))` can be used. – BlackEagle May 23 '19 at 15:34
  • .copy() is basically the same as `l2 = [l1[0], ..., l2[n]]`, which creates a new list but only assigns the elements by reference, yes. – Christoph Burschka May 23 '19 at 23:41