Immutability of Floats, Ints and Strings in Python

Ned Batchelder ned at nedbatchelder.com
Fri Nov 25 07:35:42 EST 2016


On Friday, November 25, 2016 at 7:17:08 AM UTC-5, BartC wrote:
> On 25/11/2016 11:24, Nikunj wrote:
> >
> > Out of curiosity, I wanted to understand the reason behind having different memory location for two identical floats . This is unlike ints or strings. Tried googling but couldn't find anything concrete. Any links or references would be appreciated!
> 
> Do you mean for identical floating point literals?
> 
> Some implementations will do that; see the test below. Here, Py2 and Py3 
> both give the same id for 1.3, but not for a runtime-derived 1.3. Pypy 
> will give the same id even for 1.3 at runtime (although I suspect it can 
> see past my simple expression and reduce it to 1.3).
>
> ...
> 
> ----------------------
> 
> print ("Floats:")
> x=1.3
> y=1.3
> print (id(x))
> print (id(y))
> 
> print (x is y)
> 
> z=x+1.3-y
> 
> print (id(z))
> print (x-z)
> print (x==z)
> print (x is z)
> 
> 
> print ("")
> print ("Integers:")
> x=13
> y=13
> print (id(x))
> print (id(y))
> 
> print (x is y)
> 
> z=x+13-y
> 
> print (id(z))
> print (x-z)
> print (x==z)
> print (x is z)

Ah, another complication! Literals in code objects are folded together
by the compiler, so you can share objects in one code object even when
they are not generally shared:

    >>> def f():
    ...     a = 1.3
    ...     b = 1.3
    ...     return a, b
    ...
    >>> a, b = f()
    >>> a is b
    True
    >>>
    >>> def g():
    ...     return 1.3
    ...
    >>> def h():
    ...     return 1.3
    ...
    >>> g() is h()
    False
    >>>
    >>> a, b = 1.3, 1.3
    >>> a is b
    True
    >>>
    >>> a = 1.3
    >>> b = 1.3
    >>> a is b
    False

When are objects shared? It's complicated, implementation-dependent,
and can change from version to version. Also, it doesn't matter to
real programs.

--Ned.



More information about the Python-list mailing list