0

I know I know..., this was asked a ton of time, but since I have JavaScript background I cannot get my head around what the heck is going on when we use the is to compare primitives in python

The is comparison operator is used to check if variables points to the same memory location (pretty clear huh? we should use it to check object identity), but I see a lot of <something> is not None code around and I just don't get it :/

So what's the difference between abc VS ''.join(['a', 'b', 'c']) in regards of the is operator

a = 'abc'
b = 'abc'

print( a == b)   # True
print( a is b)   # True

x = 'abc'
y = ''.join(['a', 'b', 'c'])

print( x == y )  # True
print( x is y )  # False
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Pall Arpad
  • 1,625
  • 16
  • 20
  • 2
    For the former, you use exactly the same string literal. The Python interpreter has made some optimization to make them point to the same block of memory. The latter Python interpreter cannot judge whether their results are the same in advance, so cannot do the above optimization. – Mechanic Pig Jun 07 '22 at 07:34
  • Exactly what @MechanicPig said. Only think I'd like to add is that this *optimization* is called "interning" (just in case you want to google it). – Djib2011 Jun 07 '22 at 07:40

0 Answers0