Curious Minds

Clear answers to science and history questions

Why += Works for Lists and Dicts in Python

· 6 min read · Science

In Python, the += operator is valid for lists and dictionaries because both types implement the in-place addition protocol (__iadd__), which mutates the original object rather than creating a new one—though the behavior differs subtly between the two. For lists, += extends the list in place with elements from an iterable; for dictionaries, += is not actually defined on the dict type itself, but Python’s evaluation rules make d += other equivalent to d = d + other, and since dict.__add__ exists (merging two dicts), the assignment works. This article explains the mechanics, the differences, and common pitfalls.

Background: How Python Operators Work

Python operators are just syntactic sugar for special methods. When you write a + b, Python calls a.__add__(b) (or b.__radd__(a) if needed). For augmented assignment like a += b, Python first looks for a.__iadd__(b) (in-place add). If that method exists, it is called and the result is assigned back to a. If it does not exist, Python falls back to a = a + b (using __add__). This fallback is why += works on many types that don’t implement __iadd__—including dictionaries.

Lists implement __iadd__, so list += iterable mutates the list in place and returns None (the assignment still works because the original object is modified). Dictionaries do not implement __iadd__, so dict += other is evaluated as dict = dict + other, and since dict.__add__ returns a new merged dictionary, the name is rebound to that new object.

How List += Works: In-Place Extension

For a list L, L += [1,2] is equivalent to calling L.extend([1,2]). The list object itself is modified—the memory address (id) of L does not change. This is different from L = L + [1,2], which creates a brand new list and reassigns L to it. The difference matters when you have multiple references to the same list:

a = [1]
b = a
a += [2]  # a and b both become [1,2] because a is mutated
a = a + [3]  # a becomes [1,2,3], but b remains [1,2]

The += operator on lists accepts any iterable, not just another list. So L += (1,2) or L += 'ab' works, extending with each element.

How Dict += Works: Merge and Rebind

Dictionaries do not have an __iadd__ method. So when you write d += {'x': 1}, Python does the following:

  1. Evaluate d + {'x': 1}, which calls dict.__add__.
  2. dict.__add__ creates a new dictionary that merges the keys/values of both operands (the right operand overrides the left on duplicate keys).
  3. That new dictionary is assigned back to the variable d.

Thus, d += other is exactly equivalent to d = d + other. The original dictionary object is not modified; the variable now points to a new dictionary. This is a key difference from lists.

Note: The + operator for dicts was introduced in Python 3.9 (PEP 584). Before that, d + other raised a TypeError, so d += other also failed. If you are using Python 3.8 or earlier, you must use d.update(other) or {**d, **other}.

Why This Design? Performance and Semantics

The designers of Python made lists mutable and provided __iadd__ to allow efficient in-place extension without copying the entire list. This is a common optimization for operations like building a list in a loop. For dictionaries, the merge operation is less frequently used in a loop, and the semantics of “merge and reassign” align with the idea that + is a non-mutating operation. If += on a dict mutated the original, it would be inconsistent with the fact that d1 + d2 does not modify d1.

Another reason: dictionaries are not ordered in older Python versions (pre-3.7), so an in-place merge would have to decide where to insert new keys. The reassignment approach sidesteps that by creating a new dict with a defined order (insertion order in Python 3.7+).

Common Misconceptions and Pitfalls

Many beginners assume += always mutates in place, but that is not true. The behavior depends on whether __iadd__ is implemented. For immutable types like integers, strings, and tuples, += creates a new object (because they cannot be mutated). For mutable types like lists, sets, and bytearrays, it usually mutates, but dictionaries are the exception because they lack __iadd__.

Another pitfall: using += on a dict inside a function can have surprising effects if you expect the original dict to be updated. For example:

def add_key(d):
    d += {'new': 1}  # This does NOT modify the original dict!

original = {'a': 1}
add_key(original)
print(original)  # {'a': 1} — unchanged

To actually mutate a dict, use d.update(...) or d['key'] = value.

When to Use += vs. Alternatives

For lists, += is a clean way to extend with multiple elements. It is equivalent to list.extend(), but often more readable in expressions. However, if you want to keep the original list object unchanged (e.g., when you need to preserve a reference), use list = list + other or list = [*list, *other].

For dictionaries, += is only available in Python 3.9+. It is a concise way to merge two dicts and assign the result. But if you want to modify the original dict in place, use update(). If you want to merge without modifying either, use the union operator | (also Python 3.9+) or {**d1, **d2}.

Performance Considerations

For lists, += is generally efficient because it may pre-allocate memory for the extension (like extend). However, repeated += in a loop can still be O(n²) if the list grows many times, because each extension may need to reallocate. In practice, Python’s list overallocation makes this rare, but for large loops, consider using list.extend() with a generator or building with a list comprehension.

For dicts, += creates a new dict each time, which is O(n) for the merge. If you are merging many dicts in a loop, this can be expensive. Using update() in place is O(1) per key and avoids copying the entire dict each time.

Frequently Asked Questions

Does += work on tuples?

Yes, but it does not mutate the tuple. Tuples are immutable, so t += (1,2) creates a new tuple and reassigns t. This is similar to dict behavior but for a different reason: tuples have no __iadd__ and cannot be mutated.

Why does += work on sets?

Sets are mutable and implement __iadd__, so s += {1,2} mutates the set in place, adding elements. It is equivalent to s.update({1,2}). Note that + is not defined for sets (you must use | for union), but += works because it uses __iadd__ which is defined.

Does d += {} create a new dict even if the right side is empty?

Yes. Even if the right operand is empty, d + {} creates a new dictionary that is a copy of d. The original dict is not modified. This can be a performance issue if done in a loop.

Can I use += to merge two dicts without changing the original?

Yes, d1 += d2 reassigns d1 to a new merged dict, leaving the original dict object (if referenced elsewhere) unchanged. However, if you want to keep the original variable pointing to the same object, use d1 = d1 | d2 or d1 = {**d1, **d2}.

Why does list += 'abc' add three characters, not a string?

Because += on a list iterates over the right operand and adds each element. A string is an iterable of characters, so it adds each character individually. To add the string as a single element, wrap it in a list: list += ['abc'].

Is += on a dict the same as dict.update()?

No. update() mutates the original dict in place. += creates a new dict and rebinds the variable. They produce the same resulting dict content, but the original object’s identity changes with +=.

In this article
  1. Background: How Python Operators Work
  2. How List += Works: In-Place Extension
  3. How Dict += Works: Merge and Rebind
  4. Why This Design? Performance and Semantics
  5. Common Misconceptions and Pitfalls
  6. When to Use += vs. Alternatives
  7. Performance Considerations
  8. Frequently Asked Questions