Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a pointer to a list in Python

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?

like image 243
bgcode Avatar asked Dec 04 '22 18:12

bgcode


2 Answers

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.

like image 97
Johnsyweb Avatar answered Dec 23 '22 22:12

Johnsyweb


You don't pass pointers in Python. Just assign to the slice that is the whole list

def update_list(list, data):
    list[:] = newlist
like image 31
John La Rooy Avatar answered Dec 23 '22 22:12

John La Rooy