How are arguments passed by value or by reference in Python?

Python uses a mechanism known as Call-by-Object, sometimes also called Call by Object Reference or Call by Sharing. Understanding how arguments are passed is crucial for writing predictable Python code.

If you pass immutable arguments like integers, strings or tuples to a function, the passing acts like Call-by-value. It's different when we pass mutable arguments like lists or dictionaries.

Immutable Objects (Call-by-value behavior)

With immutable objects, changes inside the function don't affect the original variable ?

def modify_number(x):
    x = 100
    print("Inside function:", x)

num = 5
modify_number(num)
print("Outside function:", num)
Inside function: 100
Outside function: 5

Mutable Objects (Call-by-reference behavior)

With mutable objects, modifications inside the function affect the original object ?

student = {'Archana': 28, 'krishna': 25, 'Ramesh': 32, 'vineeth': 25}

def test(student):
    new = {'alok': 30, 'Nevadan': 28}
    student.update(new)
    print("Inside the function:", student)
    return

test(student)
print("Outside the function:", student)
Inside the function: {'Archana': 28, 'krishna': 25, 'Ramesh': 32, 'vineeth': 25, 'alok': 30, 'Nevadan': 28}
Outside the function: {'Archana': 28, 'krishna': 25, 'Ramesh': 32, 'vineeth': 25, 'alok': 30, 'Nevadan': 28}

Reassignment vs Modification

Reassigning a parameter doesn't affect the original object, even with mutable types ?

def reassign_list(items):
    items = [7, 8, 9]  # Reassignment
    print("Inside function:", items)

def modify_list(items):
    items.append(4)    # Modification
    print("Inside function:", items)

original = [1, 2, 3]
print("Original:", original)

reassign_list(original)
print("After reassignment:", original)

modify_list(original)
print("After modification:", original)
Original: [1, 2, 3]
Inside function: [7, 8, 9]
After reassignment: [1, 2, 3]
Inside function: [1, 2, 3, 4]
After modification: [1, 2, 3, 4]

Comparison

Object Type Behavior Changes Affect Original?
Immutable (int, str, tuple) Call-by-value No
Mutable (list, dict, set) Call-by-reference Yes (if modified, not reassigned)

Conclusion

Python passes objects by reference, but the behavior depends on mutability. Immutable objects act like call-by-value, while mutable objects can be modified in-place, affecting the original.

Updated on: 2026-03-25T06:01:37+05:30

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements