Python中is和==(is not和!=)的区别

Python中有很多种运算符,本文主要记录一下is==这两种运算符的区别:

id()函数是查看该对象所在内存地址。每个对象都有对应的内存地址,如:

>>> id(1)
1543816880
>>> id("abc")
2880674151480
>>> id([1, 2, 3])
2880703493384
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

is 用于判断两个变量引用对象是否为同一个, == 用于判断引用变量的值是否相等。类似于Java中的equal()和==。反之,is not 用于判断两个变量是否引用自不同的对象,而 != 用于判断引用变量的值是否不等。

下面来几个具体的例子:

  • 整数的比较:
x = 5
y = 5
print(x == y)
print(x is y)
print(id(x))
print(id(y))

执行结果:
True
True
1543817008
1543817008
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 字符串的比较:
x = "abc"
y = "abc"
print(x == y)
print(x is y)
print(id(x))
print(id(y))

执行结果:
True
True
2039623802136
2039623802136
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • list(列表)的比较:
x = [1, 2, 3]
y = [1, 2, 3]
print(x == y)
print(x is y)
print(id(x))
print(id(y))

执行结果:
True
False
2194144817928
2194144817288
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • tuple(元组)的比较:
x = (1, 2, 3)
y = (1, 2, 3)
print(x == y)
print(x is y)
print(id(x))
print(id(y))

执行结果:
True
False
2699216284336
2699216284480
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • dict(字典)的比较:
x = {"id": 1, "name": "Tom", "age": 18}
y = {"id": 1, "name": "Tom", "age": 18}
print(x == y)
print(x is y)
print(id(x))
print(id(y))

执行结果:
True
False
3005783112296
3005783112368
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • set(集合)的比较:
x = set([1, 2, 3])
y = set([1, 2, 3])
print(x == y)
print(x is y)
print(id(x))
print(id(y))

执行结果:
True
False
2206005855176
2206006414696
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 赋值后比较(符合所有数据类型),以list为例:
x = [1, 2, 3]
y = x
print(x == y)
print(x is y)
print(id(x))
print(id(y))

执行结果:
True
True
2539215778568
2539215778568 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

总结

在上面的例子中,我们分别打印了两种运算符的比较结果和内存地址,所以可以得出:

  • 只要各对象的值一样,则 x == y 的值一定为True;
  • 如果对象的类型为整数或字符串且值一样,则 x == y和 x is y 的值为True。(经测试浮点型数值,只有正浮点数符合这条规律,负浮点数不符合);
  • list,tuple,dict,set值一样的话,x is y 则为False;
  • x == y 与 x != y 的值相反,x is y 与 x is not y 的值相反。

以上结论只针对对变量直接赋值或变量相互赋值后的比较,不针对两个变量之间拷贝后在进行比较。

猜你喜欢

转载自blog.csdn.net/xiangjai/article/details/79947713