开发者

Python is vs == [duplicate]

开发者 https://www.devze.com 2023-04-12 06:03 出处:网络
This question already has answers here: Closed 11 years ago. 开发者_高级运维 Possible Duplicate: String comparison in Python: is vs. ==
This question already has answers here: Closed 11 years ago. 开发者_高级运维

Possible Duplicate:

String comparison in Python: is vs. ==

When is the == operator not equivalent to the is operator? (Python)

I'm pretty new to Python still. I heard someone say use is, not == because "this isn't C". But I had some code x is 5 and it was not working as expected.

So, following proper Python/PEP style, when is the time to use is and when is the time to use == ?


You should use == to compare two values. You should use is to see if two names are bound to the same object.

You should almost never use x is 5 because depending on the implementation small integers might be interned. This can lead to surprising results:

>>> x = 256
>>> x is 256
True
>>> x = 257
>>> x is 257
False


The two operators have different meaning.

  • is tests object identity. Do the two operands refer to the same object?
  • == tests equality of value. Do the two operands have the same value?

When it comes to comparing x and 5 you invariably are interested in the value rather than the object holding the value.

0

精彩评论

暂无评论...
验证码 换一张
取 消