0

I have list objects a and b which look as below:

a = [1, 2, 3]
b = [1, 2, 3]
print(id(a))
print(id(b))

Output1:

1549645638528
1549650497792

Similarly, I have tuple objects a1 and b1 which look as below:

a1 = (1, 2, 3)
b1 = (1, 2, 3)
print(id(a1))
print(id(b1))

Output2:

1549643421120
1549643421120

Please help me understand why a1 and b1 are referencing to the same memory location?

And, why a and b are pointing to the different memory location?

chepner
  • 497,756
  • 71
  • 530
  • 681
meallhour
  • 13,921
  • 21
  • 60
  • 117
  • 3
    The root cause is that tuples are immutable while lists are mutable. – Learning is a mess Nov 30 '21 at 00:59
  • 5
    There's no language-level reason here. The fact that `a1` and `b1` reference the same object is entirely an implementation detail of the CPython interpreter. Other implementations are free to handle that code differently. – Brian61354270 Nov 30 '21 at 01:04
  • 3
    @Learningisamess that's what *allows* the interpreter to make this optimization but it doesn't need to. – mkrieger1 Nov 30 '21 at 01:07
  • Why would you expect `a is b`? That doesn't make any sense to me. But here's an existing question that covers it: [Why Python allocates new id to list, tuples, dict even though having same values?](/q/35477813/4518341) (Note that the title implies that tuples always get a new ID, but that's not necessarily true, as you've demonstrated.) – wjandrea Nov 30 '21 at 01:59

0 Answers0