Strange behavior involving Python nested lists -
this question has answer here:
i have following code:
distances = [[100001] * 2] * 2 edge in edges: print(distances) distances[edge[0]][edge[1]] = edge[2] print(distances) print("\n")
edges following list of tuples:
edges = [(0, 1, 10), (1, 0, -9)]
i'm expecting output:
[[100001, 100001], [100001, 100001]] [[100001, 10], [100001, 100001]] [[100001, 10], [100001, 100001]] [[100001, 10], [-9, 100001]]
but i'm getting output:
[[100001, 100001], [100001, 100001]] [[100001, 10], [100001, 10]] [[100001, 10], [100001, 10]] [[-9, 10], [-9, 10]]
any ideas what's wrong?
try code:
>>> distances[0] distances[1]
you true. means same objects when modify distances[0] modify distances[1] well. because distances[0] distances[1] cannot different.
how avoid it? change code to:
distances = [[100001] * 2] + [[100001] * 2]
now distances[0] , distances[1] 2 different objects can modify 1 without modifying in same time.
now may wonder why 2*list different list+list. can explained:
lests assume have 2 lists:
a = [100001, 100001] b = [100001, 100001] c =
it obvious when modify not modify b. modifying modify value in c because c.
now if define distances in way:
distances = a*2 # [a, a] #so distances[0] cannot different distances[1]
if define distances in way:
distances = a+b # [a, b]
Comments
Post a Comment