Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"is" operation returns false even though two objects have same id [duplicate]

Tags:

python

numpy

Two python objects have the same id but "is" operation returns false as shown below:

a = np.arange(12).reshape(2, -1)
c = a.reshape(12, 1)
print("id(c.data)", id(c.data))
print("id(a.data)", id(a.data))

print(c.data is a.data)
print(id(c.data) == id(a.data))

Here is the actual output:

id(c.data) 241233112
id(a.data) 241233112
False
True

My question is... why "c.data is a.data" returns false even though they point to the same ID, thus pointing to the same object? I thought that they point to the same object if they have same ID or am I wrong? Thank you!

like image 476
drminix Avatar asked Apr 12 '19 19:04

drminix


People also ask

Can two objects have same ID?

The identity of an object is an 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.

Why comparing two JavaScript objects will always return false?

Comparing two objects like this results in false even if they have the same data. It is because those are two different object instances, they are referring to two different objects. There is no direct method in javascript to check whether two objects have the same data or not.


1 Answers

a.data and c.data both produce a transient object, with no reference to it. As such, both are immediately garbage-collected. The same id can be used for both.

In your first if statement, the objects have to co-exist while is checks if they are identical, which they are not.

In the second if statement, each object is released as soon as id returns its id.

If you save references to both objects, keeping them alive, you can see they are not the same object.

r0 = a.data
r1 = c.data
assert r0 is not r1
like image 103
chepner Avatar answered Oct 06 '22 21:10

chepner