0

From what I read in the documents,

is operator is used to check if two values are located on the same part of the memory

So I compared two empty lists and as I expected I got False as a result.

print([] is []) # False

But why is it different for strings?

print('' is '') # True
Maran Sowthri
  • 829
  • 6
  • 14
  • 1
    Also see https://stackoverflow.com/q/15541404/494134 – John Gordon Feb 11 '23 at 05:05
  • If you want to compare _values_, then you should use `==`, not `is`. – John Gordon Feb 11 '23 at 05:05
  • If you want for a fun similar example: `x=1000; y=1000; x is y` ⇒ True, while `x=1000`\n `y=1000`\n `x is y` ⇒ False (tested on python 3.10.6). – spectras Feb 11 '23 at 05:06
  • @spectras is there a typo? Both are same statements right? – Maran Sowthri Feb 11 '23 at 05:12
  • @MaranSowthri first one is typed all on one line. Second one is typed on 3 lines. Other than that they are the same yes. – spectras Feb 11 '23 at 05:13
  • @spectras, I'm shocked! But why? – Maran Sowthri Feb 11 '23 at 05:19
  • 1
    In short, it comes from the "boxing" of the integers. All python values are wrapped in some object. In the one-liner, python wrapped the value `1000` once and handed it to both `x` and `y` (as `1000` is immutable they can share it). On separate lines, it does the boxing separately so they each get a different box. `is` tests whether the box is the same (as opposed to checking the value inside). Check out https://stackoverflow.com/questions/306313/is-operator-behaves-unexpectedly-with-integers for more. – spectras Feb 11 '23 at 05:29
  • 1
    You should eliminate the `is` operator from your short-term memory. With the exception of the `None` object, it has almost no useful use cases. – Tim Roberts Feb 11 '23 at 06:25

0 Answers0