In article <mailman.3657.1364085583.2939.python-l...@python.org>, Fabian von Romberg <fromberg...@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. -- http://mail.python.org/mailman/listinfo/python-list