How do I check if two variables reference the same object in Python?

PythonEquality

Python Problem Overview


x and y are two variables.
I can check if they're equal using x == y, but how can I check if they have the same identity?

Example:

x = [1, 2, 3]
y = [1, 2, 3]

Now x == y is True because x and y are equal, however, x and y aren't the same object.
I'm looking for something like sameObject(x, y) which in that case is supposed to be False.

Python Solutions


Solution 1 - Python

You can use is to check if two objects have the same identity.

>>> x = [1, 2, 3]
>>> y = [1, 2, 3]
>>> x == y
True
>>> x is y
False

Solution 2 - Python

Use x is y or id(x) == id(y). They seem to be equivalent.

id(object) returns a unique number (identity) that adapts the philosophy of C-style pointer. For debugging id(x) == id(y) is more convient.

x is y is prettier.


== utilizes equal comparator object.__eq__(self, other)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsnakileView Question on Stackoverflow
Solution 1 - PythonMark ByersView Answer on Stackoverflow
Solution 2 - PythonKonstantinos RoditakisView Answer on Stackoverflow