append vs + [item]
These two lines look similar, but they behave differently.
Option A:
a.append("a")
Option B:
a = a + ["a"]
What is the difference?
Option A updates the existing list in place.
Option B creates a new list, copies all elements from a, and then adds the new item.
If the length of a is K, then:
a.append("a")isO(1)amortizeda = a + ["a"]isO(K)
So even though both forms add one item, Option B is more expensive.
The same issue in a dictionary of lists
This pattern has the same problem:
dic = {}
dic[key] = dic.get(key, []) + ["a"]
dic.get(key, []) + ["a"] creates a new list every time.
Better approach: defaultdict
If you want to accumulate values efficiently, keep the existing list and append to it:
from collections import defaultdict
hashmap = defaultdict(list)
hashmap[key].append(w)
This avoids repeated list copying and keeps the code simple.