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
  question about changing the string value of a list element jacksfrustration 4 2,333 Feb-08-2025, 07:43 AM
Last Post: jacksfrustration
  Changing client.get() method type based on size of data... dl0dth 1 796 Jan-02-2025, 08:30 PM
Last Post: dl0dth
  List with equal repeatable data Ataman 6 1,777 Jun-13-2024, 07:30 PM
Last Post: Ataman
  Strange behavior list of list mmhmjanssen 3 1,759 May-09-2024, 11:32 AM
Last Post: mmhmjanssen
  Help with to check an Input list data with a data read from an external source sacharyya 3 1,860 Mar-09-2024, 12:33 PM
Last Post: Pedroski55
  No matter what I do I get back "List indices must be integers or slices, not list" Radical 4 2,782 Sep-24-2023, 05:03 AM
Last Post: deanhystad
  Delete strings from a list to create a new only number list Dvdscot 8 3,576 May-01-2023, 09:06 PM
Last Post: deanhystad
  List all possibilities of a nested-list by flattened lists sparkt 1 1,862 Feb-23-2023, 02:21 PM
Last Post: sparkt
  Сheck if an element from a list is in another list that contains a namedtuple elnk 8 3,658 Oct-26-2022, 04:03 PM
Last Post: deanhystad
Question Keyword to build list from list of objects? pfdjhfuys 3 2,754 Aug-06-2022, 11:39 PM
Last Post: Pedroski55

Forum Jump:

User Panel Messages

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