Programming

Python Is Neither Call by Value Nor Call by Reference

It’s call-by-sharing.

Yang Zhou
TechToFreedom
Published in
4 min readJan 30, 2024

--

Python Is Neither Call by Value Nor Call by Reference
Image from Wallhaven

In Python, the concept of “call by value” or “call by reference” doesn’t exactly apply as it does in languages like C or C++.

This is the root of much, if not all, confusion.

For example, in the following code snippet, a function receives a variable and changes its value:

def test_func(val):
val = val + ' 2024'
print(val)


author = 'Yang Zhou'
test_func(author)
# Yang Zhou 2024
print(author)
# Yang Zhou

As we know, call-by-reference means a function receives references to the variables passed as arguments, so modifying the arguments changes the original variables as well.

Based on the above result, the original value of the author wasn’t changed even if the test_func() changed the received variable.

Therefore, it seems Python is call-by-value, which means a copy of the object is passed to the function.

However, the following result will be surprising if it’s really called by value:

def test_func(val):
print(id(val))


author = 'Yang Zhou'
print(id(author))
# 4336030448
test_func(author)
# 4336030448

--

--