Python中不可变序列的extend方法与+=操作的差异
extend() Can't Create a New Tuple Like += Does? Great question! This boils down to core design choices for mutable vs. immutable sequences in Python, and the distinct purposes of these two operations. Let's break it down clearly:
1. The Core Purpose of extend()
The extend() method is built only for mutable sequences (like lists). Its entire job is to modify the original sequence in-place: it takes elements from an iterable and adds them directly to the existing object without creating something new.
Since immutable sequences (tuples, strings, etc.) are defined as objects that can’t be altered after creation, there’s no use case for an in-place modification method like extend(). Python doesn’t implement this method for immutable types at all—which is why you get that AttributeError: 'tuple' object has no attribute 'extend' error.
2. How += Adapts to Sequence Types
The += operator is far more flexible. For mutable sequences like lists, it uses the __iadd__ ("in-place add") special method, which does the exact same in-place modification as extend()—that’s why they’re equivalent for lists.
But for immutable sequences like tuples, which can’t support in-place changes, Python falls back to the __add__ method instead. __add__ creates a brand new object by combining the original sequence with the iterable, then reassigns the result to your variable. So for tuples, s += (3,) is actually just shorthand for:
s = s + (3,)
That’s why you end up with a new tuple instead of an error.
3. Why This Design Makes Sense
extend()is a narrow, specialized method: it exists solely to mutate mutable sequences in place. There’s no logical way to do this for immutable types, so the method isn’t provided.+=prioritizes syntax consistency across all sequence types. It adapts to whether the sequence can be modified in place or not, either altering the original object or creating a new one—so you can use the same syntax regardless of the sequence type.
As a quick sanity check, try the same logic with strings (another immutable sequence):
s = "abc" s += "def" # Works, creates a new string "abcdef" s.extend("def") # Throws AttributeError: 'str' object has no attribute 'extend'
You’ll see the exact same behavior as tuples!
内容的提问来源于stack exchange,提问作者John Cole

