'is not' or '!='

Chris Kaynor ckaynor at zindagigames.com
Mon Aug 18 18:04:28 EDT 2014


On Mon, Aug 18, 2014 at 2:42 PM, Ethan Furman <ethan at stoneleaf.us> 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.

Chris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20140818/7d511685/attachment.html>


More information about the Python-list mailing list