==和is运算符在Python中的区别

2021年4月12日11:44:12 发表评论 887 次浏览

本文概述

相等操作符(==)比较两个操作数的值并检查值是否相等。而' is '操作符则检查两个操作数是否指向同一个对象。

Python3

# python3 code to
# illustrate the
# difference between
# == and is operator
# [] is an empty list
list1 = []
list2 = []
list3 = list1
 
if (list1 = = list2):
     print ( "True" )
else :
     print ( "False" )
 
if (list1 is list2):
     print ( "True" )
else :
     print ( "False" )
 
if (list1 is list3):
     print ( "True" )
else :   
     print ( "False" )
 
list3 = list3 + list2
 
if (list1 is list3):
     print ( "True" )
else :   
     print ( "False" )

输出如下:

True
False
True
False
  • 输出首先, 如果条件为" True", 因为list1和list2均为空列表。
  • 第二, if该条件显示为" False", 因为两个空列表位于不同的存储位置。因此, list1和list2引用不同的对象。我们可以用ID()python中的函数, 返回对象的"身份"。
  • 输出第三, 如果条件是" True", 因为list1和list3都指向同一个对象。
  • 输出如果第四条件为" False", 因为两个列表的串联总是产生一个新列表。

Python3

list1 = []
list2 = []
 
print ( id (list1))
print ( id (list2))

输出如下:

139877155242696
139877155253640

这显示list1和list2引用了不同的对象。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: