Python pass by reference or value with examples

Published on Aug. 22, 2023, 12:16 p.m.

In Python, everything is passed by reference, including function parameters. However, the semantics of passing objects by reference in Python can be a bit confusing.

When we pass an object into a function as a parameter, a new reference to that object is created, which is then passed to the function. This means that if we modify the object within the function, the changes will be visible outside the function.

However, if we reassign the reference to point to a new object within the function, this will not affect the original reference outside the function. Here’s an example to illustrate this:

def func(li):
    li.append(4)
    li = [1, 2, 3]

my_list = [10, 20, 30]
func(my_list)
print(my_list)

In this example, we define a function called func() that takes a list as a parameter. Within the function, we first append the value 4 to the list using the append() method. We then reassign the li parameter to a new list [1, 2, 3].

Outside the function, we define a list my_list and pass it to the func() function. Finally, we print out the value of my_list to see if it was modified by the function.

In this case, the output will be [10, 20, 30, 4], which shows that the value 4 was appended to the list within the function. However, the list was not reassigned to a new value, so the original list is still intact.

In summary, everything in Python is passed by reference, including function parameters. However, modifying the object pointed to by a reference and reassigning a reference are two different things, and their effects can be different.

Tags:

related content