Python: why aren’t strings being internalized if they are received from ints by using str()?

62 Views Asked by At
a = "123"
b = "12" + "3"
c = str(100+20+3)

print(a is b, b is c)

Why would the output be ‘False’ in the second case?

2

There are 2 best solutions below

1
Mohit Rajput On

In Python, is operator is called the identity operator. Python interpreter assigns each object in the computer's memory a unique identification number (id). The identity operator returns true if the id() of two objects is the same else false. So, is operator tests if two variables point to the same object and not if two variables have the same value.

To illustrate

print("a:", a, type(a), id(a), a is b, a is c)
print("b:", b, type(b), id(b), b is a, b is c)
print("c:", c, type(c), id(c), c is a, c is a)  # notice the difference in id(c)

Use == operator to test if two values are the same.

0
tripleee On

The purpose of the is operator is to say whether two variables reference the same object. The only scenario where this is guaranteed is when they have been explicitly set up that way.

>>> a = "random string"
>>> b = a
>>> a is b
True

There are other scenarios wher Python might notice that two unrelated variables refer to the same value, and have them pass this test; but that is not guaranteed, merely an implementation detail which should not, and indeed cannot, be relied on.

>>> c = 1
>>> d = 1
>>> c is d
True  # or not