I declare three instances of MyClass
. I want to store each of these instances in a list variable instances
. Before the instance
is appended to the instances
I double check that it is not already in a list. Interesting, that all three instances appear to be exactly the same to Python. Why is it happening and what should we know to avoid surprises like this in a future?
instances=[]
for i in range(3):
instance=MyClass(i)
for each in instances:
if each==instance:
print 'THE SAME?', each.ID,'==', instance.ID
if instance not in instances:
print "Instance %s is not in instances"%instance.ID
instances.append(instance)
else:
print "Instance %s is already in instances"%instance.ID
index=instances.index(instance)
instanceFromList=instances[index]
print "COMPARE: instance.ID:", instance.ID, ' instanceFromList.ID:', instanceFromList.ID
print 'Number of instances stored:', len(instances)
OUTPUT:
Instance 0 is not in instances
THE SAME? 0 == 1
Instance 1 is already in instances
COMPARE: instance.ID: 1 instanceFromList.ID: 0
THE SAME? 0 == 2
Instance 2 is already in instances
COMPARE: instance.ID: 2 instanceFromList.ID: 0
Number of instances stored: 1