How to transfer the list by reference?

I am trying to implement a 'add' function that combines a list L1with L2in L3:

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

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

The above code creates an empty list instead [1,0], which means that L3it was not passed by reference.

How to pass L3by link?

+4
source share
4 answers

Lists are already passed by reference, since all Python names are links, and list objects are mutable. Use slice assignment instead of normal assignment.

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

However, this is not a good way to write a function. You should just return the combined list.

def add(L1, L2):
    return L1 + L2

L3 = add(L1, L2)
+6
source

You can achieve this with:

L3[:] = L1 + L2

Security Code:

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

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

Results:

[1, 0]
+5

, , , . list. list.extend.

def add(L1, L2, L3):
    L3.extend(L1 + L2)   # creates a new list object and copies it into L3

( ), extend -

def add(L1, L2, L3):
    L3.extend(L1)        
    L3.extend(L2)

L3.extend . L1 + L2 L3 ( , L3, ).


, :

from itertools import chain

def add(L3, *L):
    L3.extend(chain.from_iterable(L))

, :

>>> L3 = []
>>> add(L3, [1], [2], [3])
>>> L3
[1, 2, 3]

,

  • , , , , OR
  • , .

: L3[:] = ... L3 L1 + L2. , L3.extend(...) L3, , . .

, , , inplace __setitem__:

def add(L3, *L):
    L3[:] = chain.from_iterable(L)

.

+4

Python, .

Therefore, you can update the values L3, all of them in your case, so you can do it like this:

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

L3 = []

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

print L3
+1
source

Source: https://habr.com/ru/post/1692473/


All Articles