![]() |
Why changing data in a copied list changes the original list? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Why changing data in a copied list changes the original list? (/thread-34594.html) |
Why changing data in a copied list changes the original list? - plumberpy - Aug-12-2021 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. RE: Why changing data in a copied list changes the original list? - Larz60+ - Aug-12-2021 use deepcopy to create physical copy (instead of reference): https://docs.python.org/3/library/copy.html which I see you are already using. RE: Why changing data in a copied list changes the original list? - jefsummers - Aug-12-2021 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 RE: Why changing data in a copied list changes the original list? - plumberpy - Aug-14-2021 (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. |