Python a += b is not always a = a + b

In Python, the expressions a += b and a = a + b are not always equivalent, especially when dealing with mutable objects like lists. The key difference lies in how Python handles these operations internally.

Understanding the Difference

For immutable types like integers and strings, both expressions produce the same result. However, for mutable types like lists, the behavior differs significantly:

  • a = a + b creates a new object
  • a += b modifies the existing object in-place (when possible)

Case of a = a + b

When using a = a + b with incompatible types, Python raises a TypeError because it cannot concatenate different types ?

Example

x = 'Hello '
z_list = [1, 2, 3]

# This will raise an error
try:
    z_list = z_list + x
    print(z_list)
except TypeError as e:
    print(f"Error: {e}")
Error: can only concatenate list (not "str") to list

Case of a += b

The += operator calls the __iadd__ method, which can handle different types more flexibly. For lists, it iterates through the right operand and adds each element ?

Example

z_list = [1, 2, 3]
x = 'Hello'
z_list += x
print(z_list)
[1, 2, 3, 'H', 'e', 'l', 'l', 'o']

Why This Happens

The += operator treats the string as an iterable and adds each character as a separate element to the list. This is equivalent to calling z_list.extend(x) ?

# These are equivalent:
z_list1 = [1, 2, 3]
z_list1 += 'Hello'

z_list2 = [1, 2, 3]
z_list2.extend('Hello')

print("Using +=:", z_list1)
print("Using extend():", z_list2)
print("Are they equal?", z_list1 == z_list2)
Using +=: [1, 2, 3, 'H', 'e', 'l', 'l', 'o']
Using extend(): [1, 2, 3, 'H', 'e', 'l', 'l', 'o']
Are they equal? True

Comparison

Operation Behavior Creates New Object? Type Flexibility
a = a + b Concatenation Yes Strict type matching
a += b In-place extension No (for lists) Accepts any iterable

Conclusion

The += operator is more flexible than + when working with lists, as it can extend the list with any iterable object. Use += for in-place modifications and + when you need to create a new object with strict type checking.

Updated on: 2026-03-15T18:39:30+05:30

209 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements