+1 vote
ago in Programming Languages by (17.2k points)

When I test two small same strings using the "is" operator, it returns True. But when I test two big same strings, it returns False. On the other hand, the "=="  operator always True for the same strings. 

Here is an example:

>>> a="apple"

>>> b="apple"

>>> a==b

True

>>> a is b

True

>>> b="apple, banana"

>>> a="apple, banana"

>>> a is b

False

>>> a == b

True

How these two operators are different? 

1 Answer

0 votes
ago by (30.2k points)

The "is" operator returns True only if two variables are present at the same address in memory. Python internally caches small strings at the same address in the memory for optimization purposes. However, if you use longer strings, Python will not put them at the same address and the "is" operator will return False.

On the other hand, the "==" operator checks if two strings have the same values; it does not care about their memory location.

...