+4 votes
in Programming Languages by (75.1k 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


>>> a is b


>>> b="apple, banana"

>>> a="apple, banana"

>>> a is b


>>> a == b


How these two operators are different? 

1 Answer

+2 votes
by (353k points)
selected by
Best answer

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.