Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python: a += b không luôn bằng a = a + b

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ầu other là list. Trả về list mới.
  • list.__iadd__(other): Chấp nhận bất kỳ iterable nào. Gọi extend(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

Typea = a + ba += bGhi chú
int/float/str/tupleTạo mớiTạo mớiImmutable, hành vi giống nhau
listCần list, tạo mớiChấp nhận iterable, in-place+= linh hoạt hơn
dictKhông hỗ trợ +Không hỗ trợ += (Py<3.9)Py3.9+: |= cho merge
setTạ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 + b cho rõ ràng.