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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With