Fundamentals 8 min read

Understanding Python's id() Function and Parameter Passing Mechanics

This article explains Python's id() function, how objects and references work, and demonstrates parameter passing behavior with detailed code examples illustrating memory address handling for immutable and mutable types, including lists, integers, and strings, and clarifies why variable assignments may share the same address.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Understanding Python's id() Function and Parameter Passing Mechanics

The id() function returns the memory address of a Python object. Its syntax is id(object) , where object is any Python value. The function is useful for observing how Python stores objects and how variables reference them.

In Python, everything is an object and variables hold references to these objects. Even simple literals like integers and strings are objects with distinct memory addresses, which can be verified by printing id(5) or id('python') .

Examples show that two variables assigned the same immutable value (e.g., x = 2 and y = 2 ) will have identical id() values because they reference the same underlying object. For mutable objects such as lists, assigning one list to another variable (e.g., L = [1,2,3]; M = L ) makes both variables reference the same list object, so id(L) and id(M) are equal.

When a list element is changed, the list's id() remains the same because the list object itself is unchanged; only the reference of the element inside the list is updated. This explains why id(L) does not change after modifying L[0] .

Python uses a value‑passing (call‑by‑object‑reference) mechanism for function arguments. In the example:

def modify1(m, K):
    m = 2
    K = [4, 5, 6]
    return

def modify2(m, K):
    m = 2
    K[0] = 0
    return

n = 100
L = [1, 2, 3]
modify1(n, L)
print(n)   # 100
print(L)   # [1, 2, 3]
modify2(n, L)
print(n)   # 100
print(L)   # [0, 2, 3]

Calling modify1 rebinds the parameters to new objects, leaving the original arguments unchanged. Calling modify2 mutates the list object that both the argument and the caller reference, so the caller sees the change.

Overall, the article demonstrates how id() can be used to explore Python's object model, the distinction between mutable and immutable objects, and the effects of assignment and function calls on object references.

Pythonparameter passingImmutableobjectsMutableidmemory-address
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.