Home > Net >  pointers all the same in list comprehension even though they shouldn't
pointers all the same in list comprehension even though they shouldn't

Time:05-18

I think I understand pointers, here is an example showing a normal behaviour:

class A:
  def __init__(self, n):
      self.n = n
a = A(1)
b = A(1)
print(id(a))
print(id(b))

Output is:

001 | 140441581640704
002 | 140441581640608

However, when I execute this code (creating objects in a list comprehension)

class A:
  def __init__(self, n):
      self.n = n

a = [id(A(n)) for n in range(5)]

print(a)

I get this output:

[140270531148816, 140270531148816, 140270531148816, 140270531148816, 140270531148816]

Which is even worse (I guess?) because it's not even objects with the same attributes. The difference between pointers and attributes being exemplified with two exact same objects that have same attributes but are different objects so have different pointers.

CodePudding user response:

In fact, it is purely coincidental that they have the same id, Python determines whether to destroy an object by reference counting. You don't save the reference of each A(n), which causes it be destroied immediately after you get its id, so the next A(n) will use the same memory space as the previous one.

>>> [id(A(n)) for n in range(5)]
[2014694650160, 2014694650160, 2014694650160, 2014694650160, 2014694650160]
>>> [id(a) for a in [A(n) for n in range(5)]]
[2014694650208, 2014694637632, 2014694649440, 2014694653808, 2014694649536]
  • Related