does python support call by reference

Does Python support call by reference?

In Python, there is no direct support for call by reference. However, it supports passing objects by reference.

What is call by reference?

Call by reference is a method in which the reference (address) of the variable is passed to the function, and any changes made to the value of the parameter inside the function will reflect in the original variable.

What is passing objects by reference?

Passing objects by reference means that a reference (address) to the object is passed to the function, and any changes made to the object inside the function will reflect in the original object.

How does Python support passing objects by reference?

In Python, everything is an object. When an object is passed to a function, a reference to the object is passed. The reference is a pointer to the memory location of the object.


def change_list(a_list):
    a_list.append(4)

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

In the above code, we passed a list object to the function change_list(). Inside the function, we appended another element to the list. This change is reflected in the original list because we passed the reference to the list object.

What about immutable objects?

Immutable objects, such as strings and tuples, cannot be changed once they are created. So, passing them by reference does not make sense.

However, we can still simulate call by reference for immutable objects by wrapping them in a mutable container, such as a list or a dictionary.


def change_string(a_list):
    a_list[0] = "new string"

my_string = "old string"
string_list = [my_string]
change_string(string_list)
my_string = string_list[0]
print(my_string) # Output: "new string"

In the above code, we passed a list containing a string object to the function change_string(). Inside the function, we changed the first element of the list to a new string. This change is reflected in the original string because we wrapped it in a mutable container.