+ 1

[SOLVED] How to pass by value in python?

I tried to pass a list as an argument in a function but the values in the list would keep changing, I assume that's because python automatically passes any argument to be pass by reference. is there any ways to pass a list into a function by value? my desired result would be : [[0], [0], [0]] [[0], [0], [0]] [[0], [0], [0]] https://code.sololearn.com/cdXO6IpnQMe1

27th Mar 2021, 4:37 PM
Shen Bapiro
Shen Bapiro - avatar
3 Antworten
+ 3
not exactly: objects are passed by reference (and lists are object), but basic types (such as numbers, strings...) are quite passed by value... the built-in copy module could help you to shallow copy or deep copy an object. deep copy is the one you need to deeply copy an object, as you have list inside list, and you don't want to modify the original inner lists: import copy mylistcopy = copy.deepcopy(mylist) mylist.copy() do only a shallow copy, as slicing (mylist[:]) or copy.copy(mylist)
27th Mar 2021, 5:05 PM
visph
visph - avatar
+ 2
Python passes a list (or any other mutable object) by reference. You can always pass a copy if you don't want to alter your original list. a = arr.copy() Edit: Shen Bapiro ok the above didn't work and I've just seen the issue. Since you have nested lists, you need to use deepcopy. from copy import deepcopy ... def func(arr): a = deepcopy(arr) ...
27th Mar 2021, 4:54 PM
Russ
Russ - avatar
+ 1
thx for the answers guys, I managed to solved them
27th Mar 2021, 6:04 PM
Shen Bapiro
Shen Bapiro - avatar