Suppose I a function whose goal it is to modify a list in place (it doesn't just happen to modify the list in place, it's purpose is to do so). Is there a mostly agreed upon convention for which of these patterns to follow? If not, is there a mostly agreed upon convection for which of these patterns NOT to follow?
Option 1: Don't return anything
def zero_first(ls):
ls[0] *= 0
ls = [1, 2, 3]
zero_first(ls)
print(ls) # output is [0, 2, 3]
Option 2: Return the list
def zero_first(ls):
ls[0] *= 0
return ls
# User can choose, but there is not "one obvious way to do it"
ls = [1, 2, 3]
zero_first(ls)
print(ls) # output is [0, 2, 3]
# or
ls = [1, 2, 3]
ls = zero_first(ls)
print(ls) # output is [0, 2, 3]
Option 3: Return a list, but because it's being returned, explicitly copy the list
def zero_first(ls):
ls = ls.copy()
ls[0] *= 0
return ls
# Now there's only one way to do it
ls = [1, 2, 3]
ls = zero_first(ls)
print(ls) # output is [0, 2, 3]