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
  Help with to check an Input list data with a data read from an external source sacharyya 3 402 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 1,156 Sep-24-2023, 05:03 AM
Last Post: deanhystad
  Delete strings from a list to create a new only number list Dvdscot 8 1,511 May-01-2023, 09:06 PM
Last Post: deanhystad
  List all possibilities of a nested-list by flattened lists sparkt 1 915 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 1,833 Oct-26-2022, 04:03 PM
Last Post: deanhystad
Question Keyword to build list from list of objects? pfdjhfuys 3 1,556 Aug-06-2022, 11:39 PM
Last Post: Pedroski55
  Issue in changing data format (2 bytes) into a 16 bit data. GiggsB 11 2,644 Jul-25-2022, 03:19 PM
Last Post: deanhystad
  Split a number to list and list sum must be number sunny9495 5 2,279 Apr-28-2022, 09:32 AM
Last Post: Dexty
  How to check if a list is in another list finndude 4 1,836 Jan-17-2022, 05:04 PM
Last Post: bowlofred
  Different out when using conda list and pip list Led_Zeppelin 1 4,022 Jan-14-2022, 09:30 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

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