I'm trying to implement a function 'add' that combines the list L1
with L2
into L3
:
def add(L1,L2,L3):
L3 = L1 + L2
L3 = []
add([1],[0],L3)
print L3
The code above produces an empty list as a result instead of [1,0]
- This means that L3
wasn't passed by reference.
How to pass L3
by reference?
Lists are already passed by reference, in that all Python names are references, and list objects are mutable. Use slice assignment instead of normal assignment. However, this isn't a good way to write a function. You should simply return the combined list.
Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in. The following example shows how arguments are passed by reference.
Python passes arguments neither by reference nor by value, but by assignment.
Your List is an object created on heap. The variable myList is a reference to that object. In C# you never pass objects, you pass their references by value. When you access the list object via the passed reference in ChangeList (while sorting, for example) the original list is changed.
Lists are already passed by reference, in that all Python names are references, and list objects are mutable. Use slice assignment instead of normal assignment.
def add(L1, L2, L3):
L3[:] = L1 + L2
However, this isn't a good way to write a function. You should simply return the combined list.
def add(L1, L2):
return L1 + L2
L3 = add(L1, L2)
You can achieve this with:
L3[:] = L1 + L2
def add(L1, L2, L3):
L3[:] = L1 + L2
L3 = []
add([1], [0], L3)
print(L3)
[1, 0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With