Python中一行声明列表、字典、元组为何会共享引用?
Great question—this is a classic Python gotcha that trips up tons of folks when they’re starting out, so let’s break it down plainly.
First, let’s unpack what’s happening with simple values (like integers)
When you write a = b = c = 0, here’s the play-by-play:
- Python creates a single integer object with the value
0. - All three variables
a,b, andcare set to point to that same0object.
But integers are immutable—you can’t alter the value of an existing integer object. When you run a = 10, you’re not changing the original 0; you’re making a point to an entirely new integer object (10). b and c still stick to the original 0, so they stay independent of a’s change.
Now, lists, dictionaries, and (some) tuples work differently
When you do a = b = c = [], here’s what’s really going on:
- Python creates one empty list object.
- All three variables
a,b, andcpoint to that exact same list object.
Lists and dictionaries are mutable—you can modify the object itself without creating a new one. So when you run a.append('Testing'), you’re not making a point to a new list. You’re adding an element directly to the single list that all three variables are referencing. That’s why b and c show the change too—they’re looking at the same underlying object.
For tuples, it’s a bit nuanced: tuples themselves are immutable, but if a tuple contains a mutable object (like a list), the same issue pops up. For example:
a = b = c = ([],) # A tuple holding an empty list a[0].append('Testing') print(b) # Output: (['Testing'],)
Here, you’re modifying the mutable list inside the tuple, not the tuple itself. If your tuple only has immutable values (like a = b = c = (1, 2)), changing a (e.g., a = (3,4)) would create a new tuple, and b/c wouldn’t change—just like with integers.
How to fix this: Create separate objects
If you want a, b, and c to be independent lists/dicts, you need to make a unique object for each. Try either of these approaches:
- Separate line assignments:
a = [] b = [] c = [] - Unpack multiple objects in one line:
a, b, c = [], [], []
This way, each variable points to its own distinct object, so modifying one won’t affect the others.
内容的提问来源于stack exchange,提问作者Mayur Jotaniya

