"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Modify a List Within a Function in Python: Pass by Reference or In-Place Modification?

How to Modify a List Within a Function in Python: Pass by Reference or In-Place Modification?

Published on 2024-11-08
Browse:721

How to Modify a List Within a Function in Python: Pass by Reference or In-Place Modification?

Modifying a List inside a Function

When working with list parameters in functions, the references passed to the function point to the original list. Any modifications made to the list_arg variable within the function are confined to its local scope and won't affect the original list.

To circumvent this issue and modify the original list, one needs to directly assign elements to the list instead of reassigning the entire list to a new value. Here's an example:

def function1(list_arg):
   a = function2()    # function2 returns an array of numbers
   list_arg[:] = list(a)

list1 = [0] * 5
function1(list1)
print(list1)  # [1, 2, 3, 4, 5]

In this modified code, we use the slice notation list_arg[:] to assign the elements of list(a) to the original list, effectively modifying the list in place.

It's important to note that while in-place modifications may seem convenient, they can become difficult to comprehend and may lead to confusion for developers maintaining the code. Explicit reassignments are generally preferred for clarity and readability.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3