Python Forum

Full Version: Is there a way to append to a list WITHOUT modifying the parameter passed?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Let's say I have this code:

def test(some_args):
    some_args += ['two']

args = ['one']
test(args)
print(args)
When I run this code, the output is:

Output:
['one', 'two']
Is there a way to append to a list WITHOUT an in-place assignment which modifies the parameter itself? I've tried .append('two'), but that doesn't work either. I realize that I can just make a copy of the list using .copy() or with slice notation, but I want to avoid creating an extra variable just for this purpose.
what is the desired output?
By adding lists - yes you can

Output:
In [4]: list_ = [1] In [5]: list_1 = list_ + [2] In [6]: list_ Out[6]: [1]
Yes, but this requires creating another list for the purpose. Basically, I'm wondering if there is any way to emulate pass-by-value behavior somehow in Python.
Possible since 3.5 I think:

def test(some_args):
    return [*some_args, 'two']
so you want to append to the list and have the function see the effect but have the caller not see it. since the function gets the object (the list) using pass-by-reference the only real way to have that effect is to make a copy of the list. if there are no lists within the list then a shallow copy is sufficient. you can do this in the call like test(args[:]) or you do this in the function by assigning a copy to the variable it will be using below.

Python is a language that can do almost anything. it just doesn't always do it the way you want or expect.
If you don't want to modify the original why not tuple?

>>> t = ('one',)
>>> t += ('two',)
>>> t
('one', 'two')
>>> 
Hm! This actually modifies it Confused
(Sep-17-2018, 10:08 AM)wavic Wrote: [ -> ]If you don't want to modify the original why not tuple?

>>> t = ('one',)
>>> t += ('two',)
>>> t
('one', 'two')
>>> 
Hm! This actually modifies it Confused

No, it creates a new t object

Output:
In [28]: t = ('one',) In [29]: id(t) Out[29]: 140190907161512 In [30]: >>> t += ('two',) In [31]: id(t) Out[31]: 140190903830408
With lists, += will be equivalent to append (or extend)
Output:
In [34]: id(t) Out[34]: 140190903120520 In [35]: t = [1] In [36]: id(t) Out[36]: 140190903091912 In [37]: t += [2] In [38]: id(t) Out[38]: 140190903091912 In [39]: t Out[39]: [1, 2]
You are right. I missed that I used = sign so I overwitted the object. Smile
(Sep-17-2018, 11:11 AM)wavic Wrote: [ -> ]You are right. I missed that I used = sign so I overwitted the object. Smile
how witty! Big Grin
Pages: 1 2