I was trying to format the graph paths
to a series of all possible paths stored as nested lists
initially i wrote one solution with two for loops then i decided to make it into a single list comprehension when i came across this issue. My second list comper
keeps getting operated on and modified even though i copied it from comp
i even printed out the id's and compared the objects, python says they're not referencing the same object, but when i carry out any operation on comp
, comper
is also affected.
I understand that python lists are passed by reference so they have to be copied if you want a fresh new copy to work on, but why is this happening?, i don't think it's a bug because I've copied lists so many times without this behaviour
paths = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['E']
}
comp = [[key, i] for key in sorted(paths, key = None) for i in paths.get(key) if isinstance(paths.get(key), list)]
print(comp, 'this is the original comp')
comper = comp[:] # tried to copy the contents of comp into comper even tried list(comp), still get the same result
print(comper, 'comper copied, is unchanged')
if comp is comper:
print('yes')
else:
print(id(comp), id(comper))
for count, ele in enumerate(comp):
for other in comp:
if ele[-1] == other[0]:
comp[count].append(other[-1])
comp.remove(other)
# comper.remove(other) fixes the problem but why is comper getting modified even when id's are different
print(comper, 'apparently comper has changed because the operation was carried out on both')
print(comp)
print(id(comp), id(comper))
This is the output i get
[['A', 'B'], ['A', 'C'], ['B', 'D'], ['C', 'E']] this is the original comp
[['A', 'B'], ['A', 'C'], ['B', 'D'], ['C', 'E']] comper copied, is unchanged
139810664953992 139810664953288
[['A', 'B', 'D'], ['A', 'C', 'E'], ['B', 'D'], ['C', 'E']] apparently comper has changed because the operation was carried out on both
[['A', 'B', 'D'], ['A', 'C', 'E']]
139810664953992 139810664953288
comper has the extra elements because they were not removed from the list, if i uncomment the line that removes the other lists from comper
then i basically get the same result
i even printed out the id's at the bottom and they're still different