Python Forum

Full Version: Why changing data in a copied list changes the original list?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
results=[[1,2,3,4,5],
         [11,22,33,44,55],
         [111,222,333,444,555]]

#results2=results.copy()
results2=results[:]
results2[2][0]='A'
results2[2][1]='B'
results2[2][2]='C'
print(results, results2)
Using .copy() and [:], data in the original list is also changed when I changed the data in the copied list.

How can I have 2 independent copied lists?

Thanks.

P/S Found the answer.

import copy
#lst_copy = copy.deepcopy(lst)
#results2=results.copy()
results2=copy.deepcopy(results)
results2[2][0]='A'
results2[2][1]='B'
results2[2][2]='C'
print(results, results2)
What is the benefit in making a copy and changing the copied will change the original? Wish that it is just like normal copy.
use deepcopy to create physical copy (instead of reference): https://docs.python.org/3/library/copy.html
which I see you are already using.
A great video that explains the whys and hows of this is Ned Batchelder's talk from PyCon 2015 at https://www.youtube.com/watch?v=_AEJHKGk9ns
(Aug-12-2021, 01:49 PM)jefsummers Wrote: [ -> ]A great video that explains the whys and hows of this is Ned Batchelder's talk from PyCon 2015 at https://www.youtube.com/watch?v=_AEJHKGk9ns

Many thanks.