"==" versus "is"

"=="versus "is"


Problem

The snippet below confuseD me a lot:

import operator as op
a = [1,2]
b = [1,2]
print(a == b,a is b)

c = 1
d = 1
print(c == d,c is d)

And the terminal shell prompts:

True False
True True

== : compare the value of each identifier only
is : compare the physical location of each identifier

How about second scenaro? both are true?

Answer:promoting performance is a important issue in python,So python opts for directly referring to the existing variable for a new variable if their values are same.

Idea from parameter passing:python will refer a new variable to a existed variable which is immutable.[1]


  1. tuple,number,str are immutable | list,set,dict are mutable. ↩︎

posted @ 2022-10-09 14:50  44636346  阅读(21)  评论(0)    收藏  举报