[Tutor] Which is better style for a function that modifies a list?
boB Stepp
robertvstepp at gmail.com
Wed Jun 23 19:58:14 EDT 2021
I am tremendously enjoying "Practical Programming -- An Introduction
to Computer Science Using Python 3.6, 3rd Edition" by Paul Gries,
Jennifer Campbell and Jason Montojo, c. 2017. I highly recommend it
to anyone who needs to learn fundamental Python and/or introductory
computer science.
In its chapter on lists the authors point out that a function like
def remove_last_item(L: list) -> list:
"""Return list L with the last item removed."""
del L[-1]
return L
does not require the return statement since the original passed in
list will be modified in place, so there is no need for the function
to return anything. I know from experience reading the Tutor and main
lists that this is a frequent "gotcha" that catches many fellow
learners. So I wonder:
1) For such a function that mutates the passed-in list is it
clearer/better style to keep or omit the return statement? Which
reads better?
2) From a preventative of subtle bugs perspective, if one must alter
a passed-in list, would it be better to do a deep copy of the list
passed in, mutate that, and return *that* list, leaving the original
passed-in list unaltered? Of course the function documentation would
reflect this.
TIA!
boB Stepp
More information about the Tutor
mailing list