If you want changes to be made inplace, you'd need to perform operations that modify the list inplace. This would mean any of the list
instance methods. In this particular instance, you could look at list.extend
.
def add(L1, L2, L3):
L3.extend(L1 + L2) # creates a new list object and copies it into L3
Since this creates a an copy (which may be inefficient), you can instead use two extend
calls in its place -
def add(L1, L2, L3):
L3.extend(L1)
L3.extend(L2)
Calling L3.extend
modifies the original list in place. With your current code, L1 + L2
creates a new list, and re-assigns L3
to that object (and the original object that L3
was referring to was not touched).
If you'd like to generalise this to any number of lists, I'd recommend taking a look at using variable arguments:
from itertools import chain
def add(L3, *L):
L3.extend(chain.from_iterable(L))
Here's an example of how it works:
>>> L3 = []
>>> add(L3, [1], [2], [3])
>>> L3
[1, 2, 3]
As a matter of good practice, you should either
- define a function that does not modify the original structure, but returns a new value you can assign from the caller, OR
- define a function that modifies structures in place, and returns nothing.
Another user note: L3[:] = ...
will replace L3
of all its previous contents with the items from L1 + L2
. On the other hand, L3.extend(...)
will not destroy what was previously in L3
, but is instead extended by what it is passed. I'd recommend evaluating your use case and using the more appropriate method to the situation.
However, to cater to that case, you can build on the accepted answer's method using inplace assignment with __setitem__
:
def add(L3, *L):
L3[:] = chain.from_iterable(L)
Which works the same way, and should be very efficient for many lists.