2

Can someone please explain the following cases?

In case I, I thought of something reverse. For small objects, e.g., 1, python could allocate new objects for different references. But for large objects, e.g., 10000..., python could keep reusing the same memory. But case I here clearly shows the opposite.

In case II, both 'a' and 'b' refer to large objects. If case I makes sense, why assigning a tuple to 'a' and 'b' ends up with 'a' and 'b' having the same id?

Case I

>>> a = 1
>>> b = 1
>>> id(a), id(b)
(140293399709656, 140293399709656)

>>> a = 100000000000000000
>>> b = 100000000000000000
>>> id(a), id(b)
(140293400116296, 140293400116344)

Case II

>>> a = 100000000000000000
>>> b = 100000000000000000
>>> id(a), id(b)
(140293400116296, 140293400116344)

>>> a, b = 100000000000000000, 100000000000000000
>>> id(a), id(b)
(140293400116320, 140293400116320)
bohanl
  • 1,885
  • 4
  • 17
  • 33
  • 2
    Short answer: Implementation details. Don't think too hard about whether Python is reusing `int` objects unless you actually have to, and don't use `is` to compare integers. Results will be unreliable and different between different versions and implementations of Python. – user2357112 Jan 27 '14 at 03:31
  • I agree with 'implementation details'. But, remember that 'large' vs. 'small' integers really aren't that different - both are way smaller than even an empty dict. However, small numbers tend to get reused a lot - so are worth caching. Large numbers, even though they are large, tend to be unique, and so not worth caching. – Corley Brigman Jan 27 '14 at 03:44
  • Thanks. It makes sense now. But in Case II, why large numbers are still cached in tuple? – bohanl Jan 27 '14 at 03:47
  • @bohanl compile-time optimizations. More implementation-specific stuff. – roippi Jan 27 '14 at 03:54
  • Different data type. For the first case, when a = 1 and b = 1. Type(a) return . When a = 100000000000000000, Type(a) return . For the case II, in both statements on my Python, the id() return different value. – Sheng Jan 27 '14 at 04:03

0 Answers0