Python Forum
Why changing data in a copied list changes the original list?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why changing data in a copied list changes the original list?
#1
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.
Reply
#2
use deepcopy to create physical copy (instead of reference): https://docs.python.org/3/library/copy.html
which I see you are already using.
Reply
#3
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
Reply
#4
(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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to check if a list is in another list finndude 4 160 Jan-17-2022, 05:04 PM
Last Post: bowlofred
  Different out when using conda list and pip list Led_Zeppelin 1 144 Jan-14-2022, 09:30 PM
Last Post: snippsat
  Use one list as search key for another list with sublist of list jc4d 4 410 Jan-11-2022, 12:10 PM
Last Post: jc4d
  Need to parse a list of boolean columns inside a list and return true values Python84 4 265 Jan-09-2022, 02:39 AM
Last Post: Python84
  Python, how to manage multiple data in list or dictionary with calculations and FIFO Mikeardy 8 324 Dec-31-2021, 07:47 AM
Last Post: Mikeardy
  Looping through nested elements and updating the original list Alex_James 3 653 Aug-19-2021, 12:05 PM
Last Post: Alex_James
  Compile list of dictianories out of another list of dictianories by certain keys CatorCanulis 10 1,525 Jun-10-2021, 08:35 PM
Last Post: perfringo
  Reading data to python: turn into list or dataframe hhchenfx 2 1,163 Jun-01-2021, 10:28 AM
Last Post: Larz60+
  Order a list with successive permutations based on another list yvrob 3 1,125 Mar-19-2021, 08:20 AM
Last Post: supuflounder
  Saving list in a list quest_ 3 1,324 Mar-10-2021, 09:58 AM
Last Post: quest_

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020