The list that is referenced by
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
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 moduleimport 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 methodcompletedPaths.append(currentPath.copy())Both of these are shallow copies, the copy module also has
copy.deepcopy()
for list within list.