1

Would somebody please be able to explain the following behaviour in Python:

>>> 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa'
True

>>> 'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa'
False

I would expect the second case to be also True. This example is taken from the wtfpython repo, which is a collection of snippets with "surprising" behaviours. There is an open issue about a missing explanation for this particular snippet, though given the context I assume this has to do with "interning" strings. Your explanations would go towards submitting a PR, thanks!

Jonathan H
  • 7,591
  • 5
  • 47
  • 80
  • 1
    [Duplicate] This is very nicely explained on https://stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using-either-or-is-sometimes-produce – Apurva N. Saraogi Feb 25 '18 at 15:51
  • @ApurvaN.Saraogi To make sure I understand, in this particular case, the issue is the use of `is` (identity comparison) instead of `==` (equality test) as explained in [this answer](https://stackoverflow.com/a/1504848/472610), correct? – Jonathan H Feb 25 '18 at 15:54
  • @Sheljohn Correct. In the `False` example that you've posted, `id('a'*21) != id('aaaaaaaaaaaaaaaaaaaaa')`. – Alex Dubrovsky Feb 25 '18 at 16:01

0 Answers0