python is 与 == 的区别

在了解is 与 == 这两种运算符区别之前,首先要知道Python中对象包含的三个基本要素,分别是:id(身份标识)、type(数据类型) 和 value(值)

x = 123
  print(id(x))  # 4305324896    id获取变量内存地址
  print(type(x)) # <class 'int'>  typ获取e变量的类型
  • is判断的是a对象是否就是b对象,是通过id来判断的
  • ==判断的是a对象的值是否和b对象的值相等,是通过value来判断的
# 首先看下List
l1 = [1,2,3]
l2 = [1,2,3]
print("l1 id is {0}, l2 id is {1}".format(id(l1), id(l2)))  #l1 id is 4366569928, l2 id is 4366570056
print(l1 is l2) # False
print(l1 == l2)  # True

# 看下Dict
d1 = {"a":"a", "b": "b"}
d2 = {"a":"a", "b": "b"}
print("d1 id is {d1}, d2 id is {d2}".format(d1=id(d1), d2=id(d2)))   # d1 id is 4366538072, d2 id is 4366536848
print(d1 is d2)  # False
print(d1 == d2)  # True

# 测试下int
i1 = 1
i2 = 1
print("i1 id is {i1}, i2 id is {i2}".format(i1=id(i1), i2=id(i2)))  # i1 id is 4305320992, i2 id is 4305320992
print(i1 is i2) # True 当内存地址相同的时候返回True
print(i1 == i2) # True 

# 测试下str
s1 = "a"
s2 = "a"
print("s1 id is {s1}, s2 id is {s2}".format(s1=id(s1), s2=id(s2)))  # s1 id is 4364003736, s2 id is 4364003736
print(s1 is s2) # True
print(s1 == s2) # True
# 来一个特殊的str
s3 = "a "
s4 = "a "
print("s3 id is {s3}, s4 id is {s4}".format(s3=id(s3), s4=id(s4))) # s3 id is 4366553192, s4 id is 4366553304
print(s3 is s4) # False
print(s3 == s4) # True
提示:当int 在范围-5--256是同一地址,即 is 比较 True
当str 有空格, 长度超过20个字符,包含特殊字符如:#@ 都不为同一地址

相关推荐