is
zur Identitätsprüfung verwendet, um zu überprüfen, ob beide Variablen auf das gleiche Objekt zeigen, während ==
zur Überprüfung Wert verwendet wird.
Vom docs:
Der Betreiber is
und is not
Test für Objektidentität: x is y
ist true
, wenn und nur wenn x und y das gleiche Objekt. x is not y
ergibt den inversen Wahrheitswert .
>>> id(1000-1) == id(999)
False
""" What is 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.)
"""
>>> 1000-1 is 999
False
>>> 1000-1 == 999
True
>>> x = [1]
>>> y = x #now y and x both point to the same object
>>> y is x
True
>>> id(y) == id(x)
True
>>> x = [1]
>>> y = [1]
>>> x == y
True
>>> x is y
False
>>> id(x),id(y) #different IDs
(161420364, 161420012)
Aber einige kleine ganze Zahlen (-5 bis 256) und kleine Strings werden von Python im Cache: Why (0-6) is -6 = False?
#small strings
>>> x = "foo"
>>> y = "foo"
>>> x is y
True
>>> x == y
True
#huge string
>>> x = "foo"*1000
>>> y = "foo"*1000
>>> x is y
False
>>> x==y
True
'>>> 2-1 ist 1' gibt 'True' zurück lol – TehTris
@carlosdc es ist nicht genau ein Duplikat. Da funktioniert es für andere Nummern. Darum habe ich gefragt. – Rahul
@Rahul Machen Sie das klar in Ihrer Frage. – askewchan