3

When I read "Learning Python", I'm confused about using the is operator.

The book tries to explain it as a test for the same memory address (A is B, if True, means A and B are in the same memory address) but in the following case, this explanation seems to not hold. Who can help me understand this function?

  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)

  s2='ufysdjkhflakjhsdjkfhasdhfoqwhefuhalskdjfhwuioehfjkasdhfljahsdjwade'
  s1='ufysdjkhflakjhsdjkfhasdhfoqwhefuhalskdjfhwuioehfjkasdhfljahsdjwade'
  s1==s2,s1 is s2
  (True, True)

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

PS: what kind of format do strings exist in memory?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
wade
  • 49
  • 1
  • 5
    Python tries to avoid creating new string objects where possible and practical. Strings are immutable, so the same *value* may as well be the same object, saving memory and CPU time to allocate extra memory. – Martijn Pieters Jul 10 '13 at 09:04

2 Answers2

4

This is an implementation detail of CPython (the standard Python interpreter), which will reuse the same data in memory for some immutable types such as strings and integers. You can't rely on such behavior, therefore you should always use == to compare such types.

For a more in-depth answer, see https://stackoverflow.com/a/15541556/1544347

Community
  • 1
  • 1
Markus Unterwaditzer
  • 7,992
  • 32
  • 60
1

Is compares the reference, "==" is syntactical sugar for the "eq" methode.

So when you are testing with "==" the values of two string must be equal to be true. If you testing with "is" the objects must be referential the same.

glglgl
  • 89,107
  • 13
  • 149
  • 217