2

One of the benefits of immutability is memory efficiency For example

>>> a = "abcd"
>>> b = "abcd"
>>> a is b
True
>>> a = 1
>>> b = 1
>>> a is b
True

However, for tuples, it seems like python never tries to do the same thing. I wonder why?

>>> a = (1, 2)
>>> b = (1, 2)
>>> a is b
False
Keeto
  • 4,074
  • 9
  • 35
  • 58
  • 1
    It doesn't try to do the same for all ints or all strings, either. – user2357112 Apr 15 '18 at 20:41
  • You can use `==` https://pyfiddle.io/fiddle/26c865d8-770e-4e80-9509-4f386e6c7893/ – raul.vila Apr 15 '18 at 20:41
  • 3
    Such interning has a cost, namely the memory needed to store the objects and the overhead in detecting duplicate uses. Small integers and short strings are common enough to make this worthwhile; tuples are not. – chepner Apr 15 '18 at 20:43
  • @user2357112 it does that in some cases I understand but what I meant was that it never tries to perform interning with tuples. I was wondering if there were any design reasons for that – Keeto Apr 15 '18 at 20:43
  • 3
    Also, tuples are immutable; their *contents* may not be. Are `x = ([1], 2)` and `y = ([1], 2)` the same tuple? What about after `y[0].append('a')`? Even worse, the mutable part of the tuple may be nested arbitrarily deep; how much time do you want to spend determining if a tuple is wholly immutable, such that it might be worth interning? – chepner Apr 15 '18 at 20:48
  • @chepner yes, thanks for the insights – Keeto Apr 15 '18 at 20:50
  • @vaultah Interesting. This didn't seem to work on my machine. Neither for python2 or 3 – Keeto Apr 15 '18 at 20:54

0 Answers0