# 了解Python的“is”运算符

is运算符不匹配变量的值，而是实例本身。

x = [1, 2, 3] y = [1, 2, 3] print x is y #It prints false!

is运算符的文档：

print x == y

x[0] = 4 print y # prints [1, 2, 3] print x == y # prints False

>>> id(x) 4401064560 >>> id(y) 4401098192

>>> x = y >>> id(x) 4401064560 >>> id(y) 4401064560 >>> x is y True

>>> x = 'a' >>> x += 'bc' >>> y = 'abc' >>> x == y True >>> x is y False

>>> z = 'abc' >>> w = 'abc' >>> z is w True

CPython（你使用的实现，如果你不知道你正在使用的实现）自动实现小整数和一些特殊的单例如False ，但不是字符串（或大整数，或小元组，或其他任何东西）。 你可以很容易地看到这一点：

>>> a = 0 >>> a += 1 >>> b = 1 >>> a is b True >>> a = False >>> a = not a >>> b = True a is b True >>> a = 1000 >>> a += 1 >>> b = 1001 >>> a is b False

• 为了更多的可读性的比较，像x is None这样的单例值x is None
• 对于可变值，当你需要知道变异x是否会影响y

>>> x = [1, 2, 3] >>> y = [1, 2, 3] >>> print x is y False >>> z = y >>> print y is z True >>> print x is z False >>> y[0] = 5 >>> print z [5, 2, 3]

# - Darling, I want some pudding! # - There is some in the fridge. pudding_to_eat = fridge_pudding pudding_to_eat is fridge_pudding # => True # - Honey, what's with all the dirty dishes? # - I wanted to eat pudding so I made some. Sorry about the mess, Darling. # - But there was already some in the fridge. pudding_to_eat = make_pudding(ingredients) pudding_to_eat is fridge_pudding # => False

isis not Python中的两个身份运算符。 is运算符不会比较变量的值，而是比较变量的身份。 考虑这个：

>>> a = [1,2,3] >>> b = [1,2,3] >>> hex(id(a)) '0x1079b1440' >>> hex(id(b)) '0x107960878' >>> a is b False >>> a == b True >>>

>>> del a >>> del b >>> a = 132 >>> b = 132 >>> hex(id(a)) '0x7faa2b609738' >>> hex(id(b)) '0x7faa2b609738' >>> a is b True >>> a == b True >>>

>>> del a >>> del b >>> a = "asd" >>> b = "asd" >>> hex(id(a)) '0x1079b05a8' >>> hex(id(b)) '0x1079b05a8' >>> a is b True >>> a == b True >>>

x is yid(x) == id(y) ，比较对象的标识。

X指向一个数组，Y指向一个不同的数组。 那些数组是相同的，但是is运算符会查看那些不相同的指针。