Tried to do in CLI Python 2.7.6 the following command:
'foo bar'.replace(" ", "") is 'foobar'
But it returned
'foo bar'.replace(" ", "") returns
Does anyone have any logical explanation for this?
is command compares object instance references. If the two comparison terms are references to the same object instance then
is returns true. Your comparison will return true if you use the
== command, it compares the values.
- == is used to compare values.
isis for comparing references.
Then you counter me: oh, but
'foobar' is 'foobar' returns
True, but that's because Python caches small values, which
is why this comparison can be confusing, follow:
>>> s1 = 'foo' >>> s2 = 'foo' >>> s1 is s2 True >>> s1 = 'foo!' >>> s2 = 'foo!' >>> s1 is s2 False >>> 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa' True >>> 'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa' False
How far does Python cache a value? What is a great value? A small amount?
To get deeper into the subject I recommend reading this article: Internals in Python