Iteration on an instantiation Why does the console show two different objects?


I had a question as to whether iterating over the instantiation of an object would create multiple objects (I assumed no). I made this test to check:

class Foo:
    def __init__(self, msg):
        self.msg = msg
        print(self.msg, self)

    for i in range(7):
        a = Foo(i)

However, the console shows this:

0 <__main__.Foo object at 0x010BA470>
1 <__main__.Foo object at 0x010BA4F0>
2 <__main__.Foo object at 0x010BA470>
3 <__main__.Foo object at 0x010BA4F0>
4 <__main__.Foo object at 0x010BA470>
5 <__main__.Foo object at 0x010BA4F0>
6 <__main__.Foo object at 0x010BA470>

Assuming I am only instantiating one object, why does the console repeatedly report two different objects in memory (0x010BA470 and 0x010BA4F0)?

Every time you call Foo(i), it creates a new object. So in the for loop, the first cycle, it found free space at 0x010BA470 and created the object there,then assigned the object address to variable a. At the next cycle, the space at 0x010BA470 was still held by a, so it found free space at a new location 0x010BA4F0 and created the object there and assigned its address to a. The variable a now held a new object at a new location, so the space at 0x010BA470 was released. Then at the third cycle, the space at 0x010BA470 was allocated to the new object, and so on. So the two locations were alternating for new objects created in the loop.