Correct Style for Python functions that mutate the argument

The first way:

def change(array):
   array.append(4)

change(array)

is the most idiomatic way to do it. Generally, in python, we expect a function to either mutate the arguments, or return something1. The reason for this is because if a function doesn’t return anything, then it makes it abundantly clear that the function must have had some side-effect in order to justify it’s existence (e.g. mutating the inputs).

On the flip side, if you do things the second way:

def change(array):
  array.append(4)
  return array

array = change(array)

you’re vulnerable to have hard to track down bugs where a mutable object changes all of a sudden when you didn’t expect it to — “But I thought change made a copy”…

1Technically every function returns something, that _something_ just happens to be None

Leave a Comment

tech