Thursday, November 05, 2009

[Py] Comparisons -- ``=='' vs. ``is''

In Python, there two operators which check whether things are the same. One is ``=='' and another is ``is.'' They may produce identical results but actually they have different meanings.

I found an article talked about this: is is not the same as equal in Python

The simple guideline has been given by Eric:
You should really only use 'is' to check for object identity, and for any kind of value comparison, == is the way to go.
And an interesting example has been given by Kevin:
>>> "peter" == "peter"
>>> True
>>> "peter" is "peter"
>>> True

>>> "peter" is "peter1"[:-1]
>>> False
>>> "peter" == "peter1"[:-1]

>>>True
---
ref: Python built-in types: comparison


No comments:

Post a Comment