1

If strings stay in memory in a normal way,How to explain this case?

s1=';;'
s2=';;'
s1==s2,s1 is s2
(True, False)

s1=';'
s2=';'
s1==s2,s1 is s2
(True, True)
Cœur
  • 37,241
  • 25
  • 195
  • 267
wade
  • 49
  • 1

2 Answers2

2

In the first case, s1 and s2 have equal value, but are not the same instance.

In the second case, s1 and s2 also have equal value, but since they are only single-character strings, and each character is the same as itself, Python interprets this to checking that the characters are the same character, which they are.

Python does this because it uses a cache for small numbers, and single-characters.

You can read more on this question, specifically, this answer.

Community
  • 1
  • 1
Inbar Rose
  • 41,843
  • 24
  • 85
  • 131
  • 2
    Note that this is a CPython implementation detail. –  Jul 10 '13 at 11:05
  • Actually python does cache more than just single-characters strings. Try this example: `a = 'aaaaaaaaaaaaaaaaaaaaa'; b = 'aaaaaaaaaaaaaaaaaaaaa'; a is b # True Strangely, if the constant string contains a non alphanum char, it is not cached. – Samy Arous Jul 10 '13 at 11:21
  • @lcfseth String literals are also cached, they are created once and referenced by the byte code. I'm not sure whether this applies across module. –  Jul 10 '13 at 11:42
  • I had read a theory on python‘s memory manage,It said that not until 256 bytes the memory will use itself,less than 256 bytes it could allocate in a cache sink ,so how about this: s2='ufysdjkhflakjhsdjkfhasdhfoqwhefuhalskdjfhwuioehfjkasdhfljahsdjwade' s1='ufysdjkhflakjhsdjkfhasdhfoqwhefuhalskdjfhwuioehfjkasdhfljahsdjwade' s1==s2,s1 is s2 (True, True) s1='flashmanfdsafsdfasdfsdffgj;djg;alkjdfgl;kajdfl;gjkla;dfjg;lakdfj;' s2='flashmanfdsafsdfasdfsdffgj;djg;alkjdfgl;kajdfl;gjkla;dfjg;lakdfj;' s1==s2,s1 is s2 (True, False) I'm confused about it~ – wade Jul 11 '13 at 02:30
0

== operator checks for equality of value.

is checks if both entities are pointing to the same memory location.

Now, if the entities are essentially the same object, like s1=s2=";;", then s1 is s2 will be True. This is easy to understand.

But we intuitively think that two entities which were initialised separately will have different memory locations. But its not always true.

To improve performance, python just returns back a reference to the existing object, when we create an int(for some range of values), string(again for some range).

Sudipta
  • 4,773
  • 2
  • 27
  • 42