Why does my Python function change the list I passed into it?
- Expert answer
- Undergraduate
- Asked
The question
I wrote a function that appends a total to a list and returns it. After calling it, my original list outside the function has changed too, which breaks my later calculations. I thought variables inside a function were local?
Short answer
Python passes a reference to the same list object, not a copy. The name inside the function is local, but it points at the same list, so mutating it changes the original. Copy the list first, or build and return a new one.
Full expert answer
Programming tutor
BSc Computer Science, Python developer
You are right that the parameter name is local. What is not local is the object it refers to. Python variables are labels attached to objects, and passing an argument attaches a second label to the same object.
Why it happens
Lists are mutable. Methods such as append, extend, sort and item assignment change the object in place, so every label pointing at it sees the change. Reassigning the parameter with = would not affect the caller, because that only moves the local label.
Three ways to fix it
- Copy at the start of the function: items = list(items), or items.copy()
- Build a new list instead of mutating: return items + [total]
- For nested lists, use copy.deepcopy, because a shallow copy still shares the inner lists
This answer explains a method for you to apply to your own work. Copying it into a submission would count as plagiarism, and it is indexed by similarity checkers.
All questions