This program reads from a file and creates a Tunnel object for the data on each line of the file. The specifics of the program don't really matter. The output will make it clear the problem I am having.
Every time I append a new Tunnel (named temp) to the list, all the old Tunnels (also named temp which were created in previous iterations of the for loop) are changed to the new Tunnel temp. If that is confusing, please scroll down and read the output.
class Tunnel: #I am using the data from the file to create tunnel objects
def __init__ (self,x,y,d):
self.x=x
self.y=y
self.d=d
def __lt__ (self,other):
return self.d<other.d
def __repr__ (self):
return "%s %s" % (str(x),str(y))
file = open("ant.in")
n=int(file.readline())
for i in range(0,n): #this loop is irrelevant
h,t=(int(s) for s in file.readline().split())
tList=[]
mst=[]
for j in range(0,t):
x,y,d=(int(s) for s in file.readline().split())
temp = Tunnel(x,y,d) #I create a new tunnel called "temp"
print(temp) #I print it. It prints as its x and y fields.
tList.append(temp) #I try and append this new tunnel to my list
print(tList) #the list prints all the tunnels, but all the tunnels are changed to the most recent one
And the program outputs
1 2
[1 2]
2 3
[2 3, 2 3]
3 3
[3 3, 3 3, 3 3]
1 4
[1 4, 1 4, 1 4, 1 4]
The list should print
[1 2, 3 4, 3 3, 1 4]