![]() |
Keeping a value the same despite changing the variable it was equated to - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Keeping a value the same despite changing the variable it was equated to (/thread-36647.html) |
Keeping a value the same despite changing the variable it was equated to - TheTypicalDoge - Mar-13-2022 I'm beginning to learn Python and I've come across a problem that is foreign to me as a past Lua programmer. I've noticed that after appending a variable to a list, if that variable changes value so does the value in the list as well, even though the list was never directly redefined. Here's what I mean, currentPath = ["EWR", "JFK", "SFO"] completedPaths = [] completedPaths.append(currentPath) print(completedPaths) currentPath.clear() print(completedPaths) This confuses me because in Lua the list in completedPaths would stay the same until directly redefined, even if the variable it was once equated to has changed. How would I solidify the list inside of completedPaths while also changing the currentPath variable to input more values later on?
RE: Keeping a value the same despite changing the variable it was equated to - menator01 - Mar-13-2022 Might can do something like this currentPath = ["EWR", "JFK", "SFO"] completedPaths = [] # completedPaths.append(currentPath.copy()) # or maybe completedPaths = completedPaths + currentPath print(completedPaths) currentPath.clear() print(currentPath) print(completedPaths)
RE: Keeping a value the same despite changing the variable it was equated to - Yoriz - Mar-13-2022 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])) 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) or by using the copy moduleimport copy currentPath = ["EWR", "JFK", "SFO"] completedPaths = [] completedPaths.append(copy.copy(currentPath)) print(completedPaths) currentPath.clear() print(completedPaths) or the list itself's copy methodcompletedPaths.append(currentPath.copy())Both of these are shallow copies, the copy module also has copy.deepcopy() for list within list.
|