Module 4 · Scopes in Python · Lesson 3 of 3
How a function interacts with its arguments
When you pass a value into a function, the parameter is a local variable — so what happens if the function changes it? The answer is one of the most important things to understand in Python, and it depends entirely on what kind of value you passed.
Start with a plain number. The parameter gets its own copy of the value, so changing it inside the function has no effect on the caller's variable at all.
Numbers, strings and booleans all behave this way — they're immutable, and the function works on a copy. A list is different. Passing a list hands over a reference to the very same list, so a function can reach in and change the caller's data.
Same act of “passing an argument,” two outcomes: immutable values are safe because the function gets a copy; mutable ones (lists, and later dictionaries) are shared, so changes leak back out. When you want to protect a mutable original, pass — or make — a copy. Keep this in mind and a whole category of baffling bugs simply never happens.