In python, should a function modify the list or make a copy and return this?

I perform a function to execute the midpoint shift algorithm, as well as some other realistic terrain generation functions, in a 2d list (format [[n11, n12, ...], [n11, n12, ...], ...] )

My question is, is it standard in python to change the input list in this case (without return value) or is it better to make a deep copy of the list and return it?

I know that copying and returning are less efficient, however I do not want the function to be confused for others.

+4
source share
2 answers

Personally, I did this as a first approach, because many of my applications are performance-critical.

If necessary, my decision is to set the flag and do it differently according to the flag. For example, the function would be:

def func(input, deepcopy=false): if deepcopy: // deep copy the input as to_process else: // just point to_process to the input // process with the to_process 
+2
source

This is what I think a lot too. The second approach is probably cleaner and better, because clients don’t need to take anything about your function, and this does not confuse. I personally, I would prefer that. Whenever I call a function, I would like it to return a new value with the old immutable. But, it's just me.

+2
source

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


All Articles