addressof object with id()

Roy Smith roy at panix.com
Sat Mar 23 21:00:07 EDT 2013


In article <mailman.3657.1364085583.2939.python-list at python.org>,
 Fabian von Romberg <fromberg100 at hotmail.com> 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.

Yup.  This is because (in some implementations, but not guaranteed), 
Python interns strings.  That means, when you create a string literal 
(i.e. something in quotes), the system looks to see if it's seen that 
exact same string before and if so, gives you a reference to the same 
string in memory, instead of creating a new one.

Also, be careful about saying things like, "the id() function [...] 
returns [an] address.  It's only in some implementations (and, again, 
not guaranteed), that id() returns the address of an object.  All the 
docs say is, "an integer (or long integer) which is guaranteed to be 
unique and constant for this object during its lifetime".  An 
implementation is free to number objects consecutively from 1, or from 
23000, or pick random numbers, anything else it wants, as long as it 
meets that requirement.

BTW, I tried this:

>>> x = "foo"
>>> y = "foo"
>>> id(x)
3810944
>>> id(y)
3810944

which is, of course, the result I expected.  Then I tried:

>>> z = "f" + "oo"
>>> id(z)
3810944

which actually surprised me.  I had thought interning only affected 
string literals, but apparently it works for all strings!  This works 
too:

>>> a = "b" + "ar"
>>> b = "ba" + "r"
>>> id(a)
3810152
>>> id(b)
3810152

but, again, none of this is guaranteed.



More information about the Python-list mailing list