'is not' or '!='

Ethan Furman ethan at stoneleaf.us
Mon Aug 18 18:19:39 EDT 2014


On 08/18/2014 03:04 PM, Chris Kaynor wrote:
> On Mon, Aug 18, 2014 at 2:42 PM, Ethan Furman wrote:
>>
>> If you are not dealing with singletons (which is most cases), such as numbers, strings, lists, and most other
>> arbitrary objects, you will need to use "!=" or anytime the two objects you are comparing are not the exact same
>> object, you can easily get the wrong answer.
>
> For example, in CPython 3.4.1:
>>>> (254 + 3) is 257
> False
>>>> (254 + 3) == 257
> True
>>>> ('asd' + '@sd') is 'asd at sd'
> False
>>>> ('asd' + '@sd') == 'asd at sd'
> True
>
> However, when testing these cases, you need to be careful due to optimizations like smaller integer interning and string
> interning:
>
>>>> (254 + 2) == 256
> True
>>>> (254 + 2) is 256
> True
>>>> ('asd' + 'sd') == 'asdsd'
> True
>>>> ('asd' + 'sd') is 'asdsd'
> True
>
> In each of these cases, the behavior may be different in other implementations or versions of Python.

But the point to remember is that, for equal objects, '==' will work, 'is' may or may not.

--
~Ethan~



More information about the Python-list mailing list