Immutability of Floats, Ints and Strings in Python

Ned Batchelder ned at nedbatchelder.com
Fri Nov 25 06:33:32 EST 2016


On Friday, November 25, 2016 at 6:24:47 AM UTC-5, Nikunj wrote:
> Hi All,
> 
> 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!
> 
> Example:
> 
> For FLOATS:
> ==========
> 
> >>> l = 1.3
> >>> id(l)
> 140421602788216
> 
> >>> k = 1.3
> >>> id(k)
> 140421602788240
> 
> >>> k == l
> True
> 
> >>> k is l
> False
> 
> For INTS and STRINGS:
> =================
> >>> i = 2
> >>> o = 2
> >>> id(i), id(o)
> (140421602779712, 140421602779712)
> 
> >>> i is o
> True
> 
> >>> a1 = 'hi'
> >>> a2 = 'hi'
> >>> a1 is a2
> True

It's more complicated than that:

    (using Python 2.7.10)
    >>> i = 2002
    >>> o = 2002
    >>> i is o
    False
    >>> a = 'what!?'
    >>> b = 'what!?'
    >>> a is b
    False

A Python implementation can choose when to reuse immutable objects and
when not to.  Reusing a value has a cost, because the values have to
be kept, and then found again. So the cost is only paid when there's
a reasonable chance that the values will actually be needed again.
And that cost has to be weighed against the opposite cost of simply
making a new object instead.

To answer your direct question: floats are so numerous and varied, it's
reasonable to guess that you won't often need the same one.  And the cost
to make a new one is so low, that it's simpler just to not reuse any of
them.

--Ned.



More information about the Python-list mailing list