Why does a function change my list even though it returns nothing?
Quick answer
A function can change a list because the argument refers to the same mutable list object your code uses. The change is visible to the caller even if the function has no return statement. Returning a value is separate: a function that builds and returns a new list gives you a result to assign, while an in-place change updates the existing list. Python list methods such as append also modify the list and return None. [S1] [S2]
The question, the details, the next step.
A practical checklist
Find the exact list passed as the function argument.
Look for in-place changes such as
append,sort,remove, or item assignment.Check whether the function explicitly returns a value; reaching its end produces
None.Do not assign the result of a mutating list method such as
append().If you need a separate result, build and return a new list, then assign that return value.
A few more useful answers
Can a function change a list and also return a value?
Yes. A function may mutate its argument and then return something. Check the body for both in-place operations and a return statement. [S1]
Does `copy()` return a separate list?
It returns a shallow copy. That is suitable for the simple-string example here, but a shallow copy does not duplicate nested mutable objects. [S2]
Why does `sort()` return `None` when it sorted my list?
sort() modifies the list in place rather than returning a sorted list. Call it as a standalone statement when you want to change that list. [S2]
Sources
References used for this guide.
- [S1] Python Tutorial: More Control Flow Tools — function calls and return values docs.python.org · Checked
- [S2] Python Tutorial: Data Structures — list methods and mutation docs.python.org · Checked
