You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The operators is and is not test for object identity: x is y is true if and only if x and y are the same object.
We can use id(object) to get the identity of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. CPython implementation detail: This is the address of the object in memory.
And so the following are equivalent.
>>>aisb>>>id(a) ==id(b)
Remember: do not use is to compare integers. Look at the following demo:
>>>a=257>>>b=257>>>aisbFalse
This is because every time you define an object in Python, you'll create a new object with a new identity. But there are some exceptions for small integers and small strings.
The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object.
From the documentation for the is operator:
We can use
id(object)
to get the identity of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. CPython implementation detail: This is the address of the object in memory.And so the following are equivalent.
Remember: do not use
is
to compare integers. Look at the following demo:This is because every time you define an object in Python, you'll create a new object with a new identity. But there are some exceptions for small integers and small strings.
From doc, we know in CPython:
For more strange things about is, you can read Understanding Python's “is” operator, then you can understand:
More worse, you may be stuck by the following code:
Don't worry, you can find a detailed explantation here.
Ref
What does id( ) function used for?
Two variables in Python have same id, but not lists or tuples
'is' operator behaves unexpectedly with non-cached integers
“is” operator behaves unexpectedly with integers
Understanding Python's “is” operator
The text was updated successfully, but these errors were encountered: