[TriPython] Editing a list in a function

David Handy david at handysoftware.com
Wed Aug 11 13:27:49 EDT 2021


On 8/11/21 10:38 AM, Mauricio Tavares wrote:

> Thought process question: I have a list I want to massage a list
>
> def massage_list(thelist):
>      # Do things
>
> inputlist = [...]
>
> If I want to preserve the original list, would it be more logical if
>
> 1. massage_list() returns new list. If you want the output to be
> applied to inputlist, you have to do something like
>
> inputlist = massage_list(inputlist)

This is the recommended approach. It is better for functions to not 
mutate their parameters.

That general principle makes it easier to understand the program and not 
have bugs due to side effects.

>
> 2. You create a new list which is a deepcopy() of inputlist, and then
> feed it to massage_list()
>
> I am leaning towards #1 (function creates things which are returned)
> but if #2 makes more sense, do let me know before I go too far.
> _______________________________________________


More information about the TriZPUG mailing list