"is" built-in operator shows a strange behavior for the element in np.ndarray
.
Although the id of the rhs and the lhs is the same, the "is" operator returns False (this behavior is specific to np.ndarray
).
a = np.array([1.,])
b = a.view()
print(id(a[0] == id(b[0]))) # True
print(a[0] is b[0]) # False
This strange behavior even happens without the copy of view.
a = np.array([1.,])
print(a[0] is a[0]) # False
Does anyone know the mechanism of this strange behavior (and possibly the evidence or specification)?
Post Script: Please re-think the two examples.
- If this is a list, this phenomenon is not observed.
a = [0., 1., 2.,]
b = []
b.append(a[0])
print(a[0] is b[0]) # True
- a[0] and b[0] refer the exact same object.
a = np.array([1.,])
b = a.view()
b[0] = 0.
print(a[0]) # 0.0
print(id(a[0]) == id(b[0])) # True
Note: This question can be a duplication, but I'm still a bit confused.
a = np.array([1.,])
b = a.view()
x = a[0]
y = b[0]
print(id(a[0])) # 139746064667728
print(id(b[0])) # 139746064667728
print(id(a[0]) == id(b[0])) # True
print(id(a[0]) == id(x)) # False
print(id(x) == id(y)) # False
- Is a[0] a temporal object?
- Is the id for a temporal object reused?
- Doesn't it contradict to the specification? (https://docs.python.org/3.7/reference/expressions.html#is)
6.10.3. Identity comparisons
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. Object identity is determined using the id() function. x is not y yields the inverse truth value.
- If the id is re-used for the temporal objects, why in this case the id is different?
>>> id(100000000000000000 + 1) == id(100000000000000001)
True
>>> id(100000000000000000 + 1) == id(100000000000000000)
False