I’ve come across an interesting behavior with Python 3 that I don’t understand. I’ve understood that with the built-in immutable types like str, int, etc, that not only are two variables of the same value (both contain ‘x’) equal, they are literally the same object, which allows the use of the is operator. However, when I use the input() function, it seems to create a string object that is NOT the same object, but does have the same value.
Here’s my python interactive prompt of this:
$ python
Python 3.2 (r32:88452, Feb 20 2011, 11:12:31)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> x = input()
test
>>> y = 'test'
>>> x is y
False
>>> x == y
True
>>> id(x)
4301225744
>>> id(y)
4301225576
Why is this?
This is your misconception: concerning the
ints andlongs, that is valid only for a few values; with strings of any kind, it may be true concerning the strings of one module, but not otherwise.But there is a builtin function
intern()which interns any given string.