[Tutor] Which is better style for a function that modifies a list?

boB Stepp robertvstepp at gmail.com
Wed Jun 23 20:31:41 EDT 2021


On Wed, Jun 23, 2021 at 6:58 PM boB Stepp <robertvstepp at gmail.com> wrote:
>
> 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?

In light of an earlier thread I started plus now examining all of the
list methods I conclude that the Pythonic way must be to omit the
"return" statement, so that "None" is returned (Or return "None"
explicitly.) whenever a list is modified in place without returning a
new list.

> TIA!
> boB Stepp


More information about the Tutor mailing list