0

How does Python assign memory addresses for literals?

>>> id(1)
4298171352
>>> id(2)
4298171328
>>> id(1.0019)
4299162496
>>> id(1.0025)
4299162496
>>> id(1.00999)
4299162496
>>> a = 1.0025
>>> b = 1.00999
>>> id(a)
4299162496
>>> id(b)
4299162472
>>> 
jg@jg ~ $ python
Python 2.7.10 |Anaconda 2.2.0 (x86_64)| (default, May 28 2015, 17:04:42) 
[GCC 4.2.1 (Apple Inc. build 5577)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://binstar.org
>>> id(1)
4298171352

How is it that 1.0025 and 1.0999 correspond to the same memory location, but when I set a and b equal to those respective values there are now different memory locations? How is it that when I restart Python, the memory address for 1 is the same?

Also, does this mean that there is a pre-existing memory address for every integer and binned floats and character?

user1956609
  • 2,132
  • 5
  • 27
  • 43
  • 2
    Since you're not assigning the values anywhere, it can reuse the memory. – Barmar Sep 09 '15 at 20:59
  • Python caches small integers (I don't remember the exact range at the moment) and since the caching is done at startup, It seems reasonable that they'd have the same memory address from one run to the next -- but I'm no expert on how the python memory allocator works (and how it interacts with the OS's memory allocator). – mgilson Sep 09 '15 at 21:01
  • See also: http://stackoverflow.com/q/306313/748858 – mgilson Sep 09 '15 at 21:02
  • Python 2 and 3 handle integers very differently so please tag a version in your question as it is already quite broad. There is a good discussion of [the Python 2 integer implementation](http://www.laurentluce.com/posts/python-integer-objects-implementation/) on Laurent Luce's blog. – Two-Bit Alchemist Sep 09 '15 at 21:02
  • Funnily enough I can only get the same id after restarting the interpreter using python3.4, python2.7.6 always gives me a new id – Padraic Cunningham Sep 09 '15 at 21:09

1 Answers1

1

From the documentation:

Two objects with non-overlapping lifetimes may have the same id() value.

Since you're not assigning 1.0025 and 1.0999 to anything in your first test, each value's lifetime end as soon as it finishes executing the statement that prints its id(). Since their lifetimes don't overlap, Python can reuse the same memory for them, so they get the same id() values.

When you do assign them to variables, their lifetimes exist as long as those variables hold the values. As a result, they can't be put in the same memory, and id() returns different values.

Barmar
  • 741,623
  • 53
  • 500
  • 612