Nisba
Nisba

Reputation: 3448

Why one needs id() in Python if there is already hash()

The Python documentation for the id() function says

id(object) Return the “identity” of an object. This 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.

So, practically, it guaranties the uniqueness as an hash function, but only within the object lifespan and without the cool thing that an hash is hardly reconstructable.

Why should one use id()?

Upvotes: 1

Views: 611

Answers (2)

Daniel Dror
Daniel Dror

Reputation: 2507

You can think of the id function in python like a sort of pointer, it is a unique number for the that object. so two identical objects can have the same hash, but different ids (unless the hash is reference based, in which case it isn't guaranteed to return the same hash on different processes)

check this answer out as well What is the id( ) function used for?

Upvotes: 1

user2357112
user2357112

Reputation: 280311

hash is equal for equal objects, and may be equal even for unequal objects. hash doesn't even exist for mutable objects.

id is guaranteed to be unique for an object during its lifetime, and it doesn't care about mutation.

The use cases are completely different.

>>> x, y, z = 1, 1.0, [1]
>>> hash(x), hash(y)
(1, 1)
>>> hash(z)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> id(x), id(y)
(10832608, 139668416746072)
>>> id(z)
139668282136008
>>> z.append(2)
>>> id(z)
139668282136008
>>> hash(-1), hash(-2)
(-2, -2)

Upvotes: 5

Related Questions