is will return True if two variables point to the same object, == if the objects referred to by the variables are equal.

>>> a = [1, 2, 3]
>>> b = a
>>> b is a 
True
>>> b == a
True
>>> b = a[:]
>>> b is a
False
>>> b == a
True

In your case, the second test only works because Python caches small integer objects, which is an implementation detail. For larger integers, this does not work:

>>> 1000 is 10**3
False
>>> 1000 == 10**3
True

The same holds true for string literals:

>>> "a" is "a"
True
>>> "aa" is "a" * 2
True
>>> x = "a"
>>> "aa" is x * 2
False
>>> "aa" is intern(x*2)
True

相关文章:

  • 2022-12-23
  • 2021-09-06
  • 2022-03-01
  • 2022-01-04
  • 2022-02-26
  • 2021-09-17
  • 2021-07-22
  • 2021-08-28
猜你喜欢
  • 2021-12-28
  • 2022-12-23
  • 2021-09-13
  • 2021-08-08
  • 2022-01-24
  • 2021-07-25
  • 2022-01-14
相关资源
相似解决方案