0

Select the correct output of the following String operations

strOne = str("pynative")
strTwo = "pynative"
print(strOne == strTwo)
print(strOne is strTwo)

I thought it would be True,False because while it == the same "value", it is NOT referring to the same code in memory, right? or am I just missing something obvious or misunderstanding something basic?)

starball
  • 20,030
  • 7
  • 43
  • 238
  • try this print(id(strOne), id(strTwo)) – Tharanga Abeyseela Mar 16 '23 at 22:07
  • You’re not missing anything obvious. As a CPython *implementation detail*, the bytecode compiler can ‘choose’ to optimise the code by assigning string values which are equal to the same memory address. And since the `is` operator is an *identity check*; this is likely the ‘choice’ the compiler has made. – S3DEV Mar 16 '23 at 22:07
  • nevermind, I finally found my answer RIGHT after posting this. At least I think so, correct me if I am wrong but I am seeing that it is because strings are immutable and so both of these are in fact stored in same memory in a way to save space by Python, whereas when same problem but lists instead, they ARE mutable, so they are treated differently and it would instead be True,False. – Brian Bucher Mar 16 '23 at 22:11
  • oops, now I see the answer comments, they loaded late lol. Thank you both :) – Brian Bucher Mar 16 '23 at 22:12
  • sorry I have never used Stack Echange and just created this account to ask this question so I am still trying to figure out how it works. – Brian Bucher Mar 16 '23 at 22:13
  • Just keep in mind that this particular compiler optimisation is an *implementation detail*; not a design feature and should not be relied upon. Save yourself some headache and brain scratching and use the appropriate operator. :-) – S3DEV Mar 16 '23 at 22:14

0 Answers0