Home > Article > Backend Development > Why does `list_arg = list(a)` not modify the original list in `function1` in Python?
Modifying Lists as Function Parameters in Python
Consider the following code:
<code class="python">def function1(list_arg): a = function2() # function2 returns an array of numbers list_arg = list(a) # creates a new list and assigns it to list_arg list1 = [0] * 5 function1(list1) print(list1) # Output: [0, 0, 0, 0, 0]</code>
This code attempts to modify the list passed as a parameter to function1. However, if we print the list after calling function1, we find that it remains unchanged, despite the assignment within the function. This is because assigning a new list to list_arg within the function breaks the reference to the original list.
To modify the elements of the list in place, we can use assignment slicing:
<code class="python">list_arg[:] = list(a)</code>
This line assigns the elements of the new list created from a to the slice of list_arg that starts from the beginning and goes to the end. This effectively replaces the elements of list_arg with the elements of a.
Caution:
In-place list modifications can be confusing. It's generally preferred to create a new list with the desired modifications and assign it to the parameter variable, as this preserves a clear separation between the original list and the modified list.
The above is the detailed content of Why does `list_arg = list(a)` not modify the original list in `function1` in Python?. For more information, please follow other related articles on the PHP Chinese website!