Mô tả
Với immutable types (int, float, str, tuple): a += b tương đương a = a + b (tạo object mới).
Với mutable types (list, dict, set): a += b thay đổi object tại chỗ (in-place), trong khi a = a + b tạo object mới.
Trường hợp List + String
a = a + b (Lỗi)
x = 'Hello ' z_list = [1, 2, 3] z_list = z_list + x # TypeError: can only concatenate list (not "str") to list
a += b (Thành công - in-place extend)
z_list = [1, 2, 3] x = 'Hello' z_list += x print(z_list) # [1, 2, 3, 'H', 'e', 'l', 'l', 'o']
Giải thích
list.__add__(other): Yêu cầuotherlà list. Trả về list mới.list.__iadd__(other): Chấp nhận bất kỳ iterable nào. Gọiextend(other)in-place.
Ví dụ so sánh chi tiết
# List
a = [1, 2]
b = [3, 4]
# a = a + b
a1 = a
a1 = a1 + b
print("a = a + b:", a1, "id:", id(a1)) # list mới, id khác
# a += b
a2 = [1, 2]
id_before = id(a2)
a2 += [3, 4]
print("a += b:", a2, "id:", id(a2), "same id?", id(a2) == id_before) # cùng id
# Dict (Python 3.9+)
d1 = {'a': 1}
d2 = {'b': 2}
# d1 += d2 # TypeError: dict không hỗ trợ +=
# d1 |= d2 # Python 3.9+: merge in-place
d1 |= d2
print("dict |=": d1)
Bảng tóm tắt
| Type | a = a + b | a += b | Ghi chú |
|---|---|---|---|
| int/float/str/tuple | Tạo mới | Tạo mới | Immutable, hành vi giống nhau |
| list | Cần list, tạo mới | Chấp nhận iterable, in-place | += linh hoạt hơn |
| dict | Không hỗ trợ + | Không hỗ trợ += (Py<3.9) | Py3.9+: |= cho merge |
| set | Tạo mới (union) | In-place update | | vs |= |
Best Practice
- Dùng
+=cho list khi muốn extend in-place (hiệu quả bộ nhớ). - Cẩn thận khi chia sẻ reference:
a = [1]; b = a; a += [2]làm thay đổi cảb! - Với immutable: dùng
a = a + bcho rõ ràng.