深度阅读

The difference between is and==in Python

作者
作者
2023年08月22日
更新时间
8.71 分钟
阅读时间
0
阅读量

In Python, is is used for identity comparison, while == is used for value comparison.

is checks if two objects are the same object, meaning they have the same memory address. On the other hand, == compares the values of the objects to see if they are equal.

For example:

a = [1, 2, 3]
b = a
c = [1, 2, 3]

print(a is b)  # True, a and b are the same object
print(a is c)  # False, a and c are not the same object
print(a == c)  # True, a and c have the same values

Note that for some objects in Python, like integers and small strings, they may be small enough to be interned and reused by the interpreter, so is may return True even when values are different. However, this is an implementation detail and should not be relied on. In general, it’s best to use == for value comparison unless you specifically need to check object identity.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。