Python Forum
how can a variable change if I haven't changed it?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
how can a variable change if I haven't changed it?
#6
(Apr-07-2021, 06:33 PM)deanhystad Wrote: You need to do a deep copy
import copy
a = [[1, 1], [2, 2]]

b = a.copy()
print('Copy')
for x, y in zip(a, b):
    print(x, y, id(x), id(y))


print('\nDeep Copy')
b = copy.deepcopy(a)
for x, y in zip(a, b):
    print(x, y, id(x), id(y))
Output:
Copy [1, 1] [1, 1] 2858215123584 2858215123584 [2, 2] [2, 2] 2858215123072 2858215123072 Deep Copy [1, 1] [1, 1] 2858215123584 2858215122240 [2, 2] [2, 2] 2858215123072 2858215123520
When you copy a list of lists the copy is a new list that contains lists from the original. To create copies of the contents you should use deepcopy from the copy library. Notice that the object ID's match when doing b = a.copy(), but when doing b = copy.deepcopy(a), new lists are created for the copy.

Thanks pal, you've solved my problem and taught me a lesson.
Reply


Messages In This Thread
RE: how can a variable change if I haven't changed it? - by niminim - Apr-07-2021, 06:57 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Comparing two Pandas df’s and returning only changed records hobbycoder 1 688 Oct-29-2024, 01:55 PM
Last Post: deanhystad
  Help with writing monitored data to mysql upon change of one particular variable donottrackmymetadata 3 1,390 Apr-18-2024, 09:55 PM
Last Post: deanhystad
  The behavior of tune model has changed Led_Zeppelin 5 5,979 Oct-21-2021, 06:52 PM
Last Post: jefsummers
  Change variable value during a while loop? penahuse 2 5,259 Nov-15-2020, 11:53 PM
Last Post: penahuse
  Change variable in an outside file ebolisa 5 4,291 Nov-11-2020, 04:41 AM
Last Post: ebolisa
  Change name of variable samuelbachorik 2 2,761 Aug-10-2020, 02:34 PM
Last Post: deanhystad
  Python - change variable type during program execution ple 1 3,245 Apr-12-2020, 08:43 AM
Last Post: buran
  I haven't a clue how to implement this logic 357mag 3 2,919 Apr-02-2020, 04:35 PM
Last Post: 357mag
  trying to change variable value with a def pythonbegginer 11 6,248 Mar-07-2020, 02:54 PM
Last Post: pythonbegginer
  RuntimeError: dictionary changed size during iteration Shreeniket987 3 5,920 Jun-01-2019, 01:22 PM
Last Post: buran

Forum Jump:

User Panel Messages

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