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)
4
  • 1
    Some languages cache certain objects. Python might as well cache one-symbol strings. Commented Jul 10, 2013 at 11:01
  • 4
    Wait, isn't this basically the same as your previous question? Commented Jul 10, 2013 at 11:05
  • Are you trying to ask what by what rules CPython decides to intern a string? Commented Jul 10, 2013 at 11:23
  • See when does Python allocate new memory for identical strings? for that specific question. Commented Jul 10, 2013 at 11:24

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Note that this is a CPython implementation detail.
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.
@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.
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~
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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.