Python定义函数时为何修改内部列表会影响外部变量?
Let's break down exactly what's happening here—this is a super common gotcha with how Python handles mutable objects, so you're definitely not alone in being confused!
First example: Why does a change unexpectedly?
In Python, mutable objects like lists, dictionaries, and sets are handled by object reference. When you write d = c inside your function, you're not creating a copy of the list—you're just making d point to the exact same list object that c (and your external variable a) points to.
Think of it like having two different nicknames for the same notebook: if you write in the notebook using one nickname, the changes will show up when you grab it using the other nickname. Here, a, c, and d are all just nicknames for the same list sitting in your computer's memory. So when you run d[0] = 10, you're modifying that shared list's content—of course a will reflect that change too.
Your confusion about "local variable scope" makes total sense, but you're mixing up two things: the variable itself, and the object it points to. d is indeed a local variable (it only exists inside the function), but the list it references was created outside the function's scope. Modifying the object's content doesn't care about variable scope—it only cares about which object you're pointing to.
Second example: Why does a stay unchanged?
When you use d = list(c), you're explicitly creating a new list object that's a copy of the original. Now d points to this fresh, separate list in memory, with no link to the original a. Any changes you make to d only affect this new copy, so the original a stays exactly as it was.
Quick clarity check with immutable objects
This behavior only applies to mutable types. If you were working with immutable objects like integers, strings, or tuples, you wouldn't see this cross-scope modification:
a = 2 def changeA(c): d = c d = 10 changeA(a) print(a) # Outputs 2
Here, reassigning d = 10 creates a brand-new integer object and points d to it—since integers are immutable, you can't modify the original 2, only switch to pointing to a new value.
内容的提问来源于stack exchange,提问作者Aloizio Macedo

