Python list gotcha

Suppose in python you're building a list of buckets:

>>> a = [[]] * 10
>>> print a
[[], [], [], [], [], [], [], [], [], []]

Looks good. However:

>>> a[5].append(1)
>>> print a
[[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]

Surprising? What happens here is that multiplying the list replicates the reference to the same empty list. You have the exact same mutable list replicated 10 times: instead of 10 buckets, you have 10 references to 1 bucket: therefore if appending to one it looks like one appends to all.

What you need here is a way to invoke the list constructor [] multiple times:

>>> a = [[] for i in range(10)]
>>> print a
[[], [], [], [], [], [], [], [], [], []]
>>> a[5].append(1)
>>> print a
[[], [], [], [], [], [1], [], [], [], []]

a mistake like this can take quite a bit of time to track down.