You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

列表追加元组:l = l + tup与l += tup的差异及报错原因

Why l = l + tup Errors but l += tup Works in Python

Great question—so many Python developers assume += is just shorthand for l = l + ..., but they’re actually using entirely different mechanisms under the hood. Let’s break this down:

1. The Problem with l = l + tup

When you use the + operator with a list, you’re calling the list.__add__() method. This method has a strict rule: it only accepts another list as the right-hand operand. Its job is to create and return a new list by concatenating two existing lists.

Since your right-hand value is a tuple (('a', 'b')) instead of a list, Python throws that TypeError—it can’t concatenate a list and a tuple using the + operator.

2. Why l += tup Works

The += operator calls the list.__iadd__() method (short for "in-place add"). This method is designed to be far more flexible: it accepts any iterable (tuples, strings, generators, sets—anything you can loop over) instead of just lists.

What __iadd__ actually does is iterate over the right-hand operand and add each element to the original list directly (it modifies the list in place, rather than creating a new one). This is exactly the same behavior as calling l.extend(tup)—which is why your tuple works perfectly here.

Quick Example to Prove It

Try this out to see the flexibility in action:

l = []
l += "hello"  # Strings are iterable!
print(l)  # Output: ['h', 'e', 'l', 'l', 'o']

# But this would throw the same TypeError as before:
l = l + "hello"

To sum up: + is for strict list-to-list concatenation, while += is for in-place extension with any iterable. That’s the key difference that’s causing the error in one case but not the other.

内容的提问来源于stack exchange,提问作者London guy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:22:08