does python use call by reference

Does Python use Call by Reference?

Python is a programming language that is widely popular for its simplicity and ease of use. One of the concepts in programming is the passing of arguments to functions. In Python, there is a debate on whether it uses call by reference or not.

Let's dive into the concept of call by reference first. In call by reference, the memory address of the variable is passed to the function, and the function can modify the original value of the variable. This means that any changes made to the parameter within the function will affect the original value outside of the function as well.

Python uses call by object reference

In Python, everything is an object, and variables are just references to these objects. When you pass a variable to a function, you pass a reference to the object it points to. This is known as "call by object reference."

Consider the following example:


def change_list_inplace(lst):
    lst.append(4)

my_list = [1, 2, 3]
change_list_inplace(my_list)

print(my_list)  # Output: [1, 2, 3, 4]

Here, the function `change_list_inplace` takes a list as an argument and modifies it by appending a value to it. When we pass `my_list` to the function, we are passing a reference to the list object. The function modifies this object, which reflects in the original list outside of the function.

Immutable objects are passed by value

However, Python treats immutable objects differently. Immutable objects like integers, strings, and tuples cannot be modified in place. So when we pass them to a function, a new copy is created, and the function operates on this copy. Any changes made to the parameter within the function will not affect the original value outside of the function.

Consider the following example:


def change_int(a):
    a += 1

my_int = 5
change_int(my_int)

print(my_int)  # Output: 5

Here, the function `change_int` takes an integer as an argument and tries to modify it by adding 1 to it. However, since integers are immutable in Python, a new copy of the integer is created, and the original value outside of the function remains unchanged.

Conclusion

So, in conclusion, Python uses call by object reference for mutable objects and call by value for immutable objects. Understanding this concept is crucial when working with functions in Python.