[BangPypers] python id function
Anand Chitipothu
anandology at gmail.com
Thu Jan 7 13:28:32 CET 2010
On Thu, Jan 7, 2010 at 1:44 PM, leela vadlamudi
<leela.vadlamudi at gmail.com> wrote:
> Hi,
>
> Python docs says that id function returns the unique id for an object.
>
>>>> id(10)
> 165936452
>>>> a=10
>>>> id(a)
> 165936452
>>>> b = int(10)
>>>> id(b)
> 165936452
>
>>>> x = tuple()
>>>> y=tuple()
>>>> id(x)
> -1208311764
>>>> id(y)
> -1208311764
>
>>>> l = list()
>>>> m = list()
>>>> id(l)
> -1210839956
>>>> id(m)
> -1210839700
>
> >From the above example, id(mutable_object) returns different ids, but
> id(immutable_object) return always the same id. If I try to create new
> immutable object, It is just returning the existed object instead of
> creating new. How does it internally manages to return the same object? Why
> it is not creating new object if it is immutable?
>
> What about this below case?
>
>>>> id((1,))
> -1208770004
>>>> id((1,))
> -1208770004
>>>> a=(1,)
>>>> id(a)
> -1208745460
>>>> id((1,))
> -1208759028
>
> Why is id changes here even if it is a tuple(immutable)
Most of the times id function returns the memory location used by that
object. In most of your examples, the tuple was getting allocated
again at the same location.
>>> id((1, 2, 3))
601544
>>> id((1, 2, 3))
601544
>>> id((1, 2, 33))
601544
>>> id((1, 2, 42))
601544
Notice that it is returning the same id even if the contents of tuple
are different. Same thing works for lists too. Immutability doesn't
really matter.
>>> id([1, 2, 3])
601584
>>> id([1, 2, 3])
601584
>>> id([1, 2, 3])
601584
>>> id([1, 2, 33])
601584
>>> id([1, 2, 42])
601584
But try allocating some between these calls and the id changes.
>>> id((1, 2, 3))
601544
>>> a = (1, 2, 3)
>>> id((1, 2, 3))
628096
>>>
>>> id([1, 2, 3])
601584
>>> x = [1, 2, 3]
>>> id([1, 2, 3])
598544
Anand
More information about the BangPypers
mailing list