63

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.

Barm
  • 403
  • 5
  • 11
snakile
  • 52,936
  • 62
  • 169
  • 241

2 Answers2

80

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
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • 2
    identity mean id() ? – iperov Feb 07 '21 at 15:17
  • 1
    `id(x)` returns a value that is unique to `x` for its lifetime, so yes, as long as `x` and `y` exist at the same time. (Two objects that do *not* overlap in time can have the same `id` value.) – chepner Apr 28 '22 at 15:46
3

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)

  • 1
    Avoid using the pattern `id(...) == id(...)` in general. For example, `id(foo()) == id(foo())` could be true without `foo() is foo()` being true: since the lifetime of the objects returned by `foo` may not overlap, Python is free to recycle the `id()` value for use with both objects. – chepner Apr 28 '22 at 15:51