Yandex

Python id() Function – Get Memory Address of an Object



Python id() Function

The id() function in Python returns a unique identifier for a given object. This identifier is the object's memory address, which remains constant during the object's lifetime.

Syntax

id(object)

Parameters:

  • object – Any Python object (string, list, number, etc.)

Returns:

  • An integer that represents the identity of the object.

Example 1: Using id() with Integers

x = 10
print(id(x))
140709661559888

(Output will vary depending on your system)

Example 2: Same Value, Same ID?

a = 100
b = 100
print(id(a) == id(b))
True

In CPython, small integers and strings are cached, so variables with the same value may share the same ID.

Example 3: Different Objects

x = [1, 2, 3]
y = [1, 2, 3]
print(id(x) == id(y))
False

x and y are different list objects, even though they have the same content.

Why Use id()?

  • To compare if two variables refer to the same object (especially with is)
  • For debugging object references and identity issues
  • To understand Python’s memory model

Important Notes

  • IDs are guaranteed to be unique and constant for the object during its lifetime.
  • Once an object is garbage collected, its ID may be reused.

Interview Tip

In Python interviews, id() is often discussed in the context of is vs == comparisons, especially for mutable vs immutable types.

Summary

  • id(object) returns the unique identity (memory address) of the object.
  • Useful for checking object identity, especially with is keyword.
  • May give the same result for immutable types with the same value.

Practice Problem

Create two variables with the same value. Check if their IDs are equal. Then change one value and compare again.

a = "hello"
b = "hello"
print("Before change:", id(a) == id(b))

b = b + "!"
print("After change:", id(a) == id(b))


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M