Pythonの比較演算子『==』と『is』の違いがよくわからないので、なんとなく調べてみた
>>> 1 is 1 True >>> 1 == 1 True >>> a = 1 #integer variable >>> b = 1 >>> a == b True >>> a is b True >>> a = "abc" #character variable >>> b = "abc" >>> a == b True >>> a is b True >>> a = [1,2,3] #sequence >>> b = a[:] #copy >>> c = a #reference >>> a == b True >>> a is b # <- Right here! False >>> a is c True
なんとなくわかったような気がするけど、『is』を使う機会ってあんましなさそう?(´・ω・`)
追加
id()って何?ってとこから調べてみた
(>>> c = [1] 以下は関係ないけど一応実験的に)
>>> id() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: id() takes exactly one argument (0 given) >>> id <built-in function id> >>> help(id) Help on built-in function id in module __builtin__: id(...) id(object) -> integer Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (Hint: it's the object's memory address.) >>> a = 1 >>> b = 1 >>> id(a) == id(b) True >>> id(a) is id(b) False >>> c = [1] >>> d = [1] >>> id(c) == id(d) False >>> id(c) is id(d) False >>> e = "hoge" >>> f = "hage" >>> id(e) is id(f) False >>> id(e) == id(f) False
こんなんでどうでしょう?