I want to read a graph, whose vertexes are numbered 0..n-1. I tried the following code:
myfile = open('test.in', 'r')
n = int(myfile.readline())
graph = [[]]*n
for line in myfile:
u, v, w = map(int, line.strip().split(' '))
graph[u].append((v, w))
print graph
but it doesn’t work well. I found that all elements in graph are the same! Then I use the following code to fix it:
road = [[] for i in xrange(n)]
It does work, but looks not so pretty.
I want to know if there is a better solution to this situation and why all elements are the same in the first code?
You could use
The reason that
graph = [[]]*ndoesn’t work is that you are creating a single empty list and then making many references to that same list