Passing a pointer to a list in Python

Is there a way to pass a pointer to a list so that I can update_list(list, data)

Instead of doing list = update_list(list, data)

Regardless of whether it is possible that Pythonic is desirable in this situation?

+4
source share
5 answers

I recommend reading the semantics of Python variable names from a C ++ perspective :

All variables are references.

This is a simplification of the entire article, but this (and understanding that list is volatile ) 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 with the extend () method:

 In [9]: def update_list(lst, data): ...: lst.extend(data) ...: 

In fact, the need for your function is probably eliminated.

NB: list is inline and therefore a poor choice for a variable name.

+10
source

You do not pass pointers in Python. Just assign a slice, which is a complete list.

 def update_list(list, data): list[:] = newlist 
+3
source

Of course, just use the correct variable names ( list type):

 >>> def update_list(lst): ... lst.append('hello') ... >>> a = [] >>> update_list(a) >>> a ['hello'] >>> 

I am not a big fan of modifying things in place, and I would prefer the second method over the first.

+1
source

Besides accounting for the fact that a list is mutable and that you can change it in place inside other functions, as already indicated by other answers; if you write a lot of update_list methods, you need to think about whether the data that is being stored is not stored, but something else that fits into the model you created as part of an object-oriented approach to the problem.

If so, then, in any case, create your own class and methods to provide the interface you need for 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) 
+1
source

fooobar.com/questions/499 / ... will help you in the right direction understand the Python way of executing Python with the values ​​passed in.

In general, Putin’s way of updating the list would be to write / call update_list(list, data) .

0
source

Source: https://habr.com/ru/post/1387831/


All Articles