addressof object with id()

Dave Angel davea at davea.name
Sat Mar 23 20:49:53 EDT 2013


On 03/23/2013 08:37 PM, Fabian von Romberg wrote:
> Hi,
>
> I have a single questions regarding id() built-in function.
>
> example 1:
>
> var1 = "some string"
> var2 = "some string"
>
> if use the id() function on both, it returns exactly the same address.
>
>
> example 2:
>
> data = "some string"
> var1 = data
> var2 = data
>
> if use the id() function on var1 and var2, it returns exactly the same address.
>
>
> can anyone explain me please why does this happens?   Is this correct?
>
>

The Python system may decide to optimize new objects by reusing old 
ones, IF the type is immutable.  This ends up saving a good bit of 
space.  Three places that come to mind are strings, small ints, and 
booleans.  In fact for booleans, it's required behavior.  There is 
exactly one True object, and one False object.

You can assume that if the id's are equal, the objects are equal.  But 
you can't assume the inverse or the converse.

So it also turns out to save some time.  When two objects are being 
compared for equal, and it turns out they have the same id, there's no 
need to actually look at the contents.


-- 
DaveA



More information about the Python-list mailing list