Python Forum
Keeping a value the same despite changing the variable it was equated to
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Keeping a value the same despite changing the variable it was equated to
#3
The list that is referenced by currentPath that is appended to the list referenced by completedPaths is not a copy of the list it is the same list.
currentPath = ["EWR", "JFK", "SFO"]
completedPaths = []
 
completedPaths.append(currentPath)
print(id(currentPath))
print(id(completedPaths[0]))
Output:
2794339074624 2794339074624
You can view this here this visualizer will show you that the same list object is being referenced by currentPath and index 0 of completedPaths.

If you don't want this behaviour rather than passing the reference to the list pass a copy by using a slice of all items
currentPath = ["EWR", "JFK", "SFO"]
completedPaths = []
 
completedPaths.append(currentPath[:])
print(completedPaths)
 
currentPath.clear()
print(completedPaths)
Output:
[['EWR', 'JFK', 'SFO']] [['EWR', 'JFK', 'SFO']]
or by using the copy module
import copy

currentPath = ["EWR", "JFK", "SFO"]
completedPaths = []
 
completedPaths.append(copy.copy(currentPath))
print(completedPaths)
 
currentPath.clear()
print(completedPaths)
Output:
[['EWR', 'JFK', 'SFO']] [['EWR', 'JFK', 'SFO']]
or the list itself's copy method
completedPaths.append(currentPath.copy())
Both of these are shallow copies, the copy module also has copy.deepcopy() for list within list.
Reply


Messages In This Thread
RE: Keeping a value the same despite changing the variable it was equated to - by Yoriz - Mar-13-2022, 10:50 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Keeping up with IDEs and Virtual Environments... bytecrunch 7 2,816 Sep-05-2022, 08:04 PM
Last Post: snippsat
  Problem keeping the window up benlyboy 11 4,371 Jan-24-2020, 02:12 AM
Last Post: tamilselvisubbiah
  Changing a variable's name on each iteration of a loop rix 6 85,920 Jan-03-2020, 07:06 AM
Last Post: perfringo
  merging lists, dedup and keeping order, in older pythons Skaperen 3 3,270 Oct-19-2018, 01:30 AM
Last Post: ODIS
  Keeping Intersection of an Image Only Anysja 4 3,071 Aug-15-2018, 09:47 PM
Last Post: Anysja
  help with keeping score W3BL3Y 2 6,420 Apr-29-2018, 01:12 PM
Last Post: W3BL3Y
  int(variable) not changing variable to an integer StoopidChicken 2 3,047 Jan-11-2018, 10:30 AM
Last Post: StoopidChicken
  Questions on variable changing between files. Sello 12 7,332 Apr-25-2017, 04:59 AM
Last Post: wavic
  changing variable outside of a function tkj80 8 7,453 Jan-05-2017, 03:52 AM
Last Post: tkj80

Forum Jump:

User Panel Messages

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