0

doing:

>>>'a'*20 is "aaaaaaaaaaaaaaaaaaaa"

gives

>>>True

while doing:

>>>'a'*21 is "aaaaaaaaaaaaaaaaaaaaa"

gives

>>>False

Whats going on here? Is this a bug?

Ritesh
  • 311
  • 1
  • 10
  • 4
    There is no bug. Python don't create new objects in memory for short strings and int numbers less then 256. – NobbyNobbs Jun 15 '18 at 05:46
  • 2
    just to add to @NobbyNobbs : `is` implies the same memory object, the correct "equality check" is with `==` – Ofer Sadan Jun 15 '18 at 05:49
  • check this out it will give an idea https://stackoverflow.com/questions/306313/is-operator-behaves-unexpectedly-with-integers – Murali Jun 15 '18 at 05:52

1 Answers1

1

For smaller objects python is reusing the allocated memory. But for larger objects the reference is changing. Do check this

x='aaaaaaaaaaaaaaaaaaaaa'
y='a'*21
t= 'a'*20
u = 'aaaaaaaaaaaaaaaaaaaa'

Here t and u reference the same string but x and y do not so the object comparison isn't working.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Abhinav
  • 11
  • 1
  • 1
  • 1
    Please refrain from answering obvious FAQs. If you find that the answers to the proposed duplicates are not good enough, post your answer there. – tripleee Jun 15 '18 at 06:20