Is there any way to pass a pointer to a list, so I could have
update_list(list, data)
Instead of having to do
list = update_list(list, data)
Independent of whether this is possible, what is advisable and Pythonic in this situation?
Is there any way to pass a pointer to a list, so I could have
update_list(list, data)
Instead of having to do
list = update_list(list, data)
Independent of whether this is possible, what is advisable and Pythonic in this situation?
I recommend reading Semantics of Python variable names from a C++ perspective:
All variables are references
This is oversimplification of the entire article, but this (and the understanding that a list
is a mutable type) should help you understand how the following example works.
In [5]: def update_list(lst, data):
...: for datum in data:
...: lst.append(datum)
...:
In [6]: l = [1, 2, 3]
In [7]: update_list(l, [4, 5, 6])
In [8]: l
Out[8]: [1, 2, 3, 4, 5, 6]
You can even shorten this by using the extend() method:
In [9]: def update_list(lst, data):
...: lst.extend(data)
...:
Which actually probably removes the need of your function.
N.B: list
is a built-in and therefore a bad choice for a variable name.
You don't pass pointers in Python. Just assign to the slice that is the whole list
def update_list(list, data):
list[:] = newlist
Sure, just make sure to use proper variable names (list
is a type):
>>> def update_list(lst):
... lst.append('hello')
...
>>> a = []
>>> update_list(a)
>>> a
['hello']
>>>
I'm not a big fan of modifying things in-place and I would actually prefer the second method over the first.
Aside from taking into account that a list
is mutable and that you can modify it in place inside other functions, as has been already pointed out by other answers; if you're writing many update_list
methods, you have to consider if the data that is being stored is not really a list but something else that fits into the model you've created as part of the object oriented approach to the problem.
If that's the case, then by all means create your own class and methods to provide the interface that you need to the internal state of your object:
class MyList(list):
def update(self, data):
# Whatever you need to update your data
...
my_list = MyList()
my_list.update(data)
This StackOverflow question and subsequent accepted response will guide you in the right direction to understanding the Pythonic way of what Python does with values passed in.
In general, the Pythonic way to update the list would be to write/call update_list(list, data)
.