Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a list by reference?

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?

like image 787
user6039980 Avatar asked Jan 21 '18 02:01

user6039980


People also ask

Are lists pass 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.

How do you pass by reference?

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.

Is Python list pass by reference?

Python passes arguments neither by reference nor by value, but by assignment.

Is list passed by reference C#?

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.


2 Answers

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)
like image 59
chepner Avatar answered Sep 28 '22 19:09

chepner


You can achieve this with:

L3[:] = L1 + L2

Test Code:

def add(L1, L2, L3):
    L3[:] = L1 + L2

L3 = []
add([1], [0], L3)
print(L3)

Results:

[1, 0]
like image 26
Stephen Rauch Avatar answered Sep 28 '22 18:09

Stephen Rauch