pythonpython-object

Python( Gotcha?) - Element gets appended to multiple list items, in a list of list


I've recently hit a gotcha in Python. I've added a minimal example. Can somebody tell me what is happening?

a = [list()] * 3
print(a)
#[[], [], []]
a[0].append(1)
print(a)
#Out - [[1], [1], [1]]
#Expected - [[1],[],[]]

Solution

  • The line a = [list()] * 3 takes the inner list built by list() and repeats it three times, therefore a is a (outer) list holding three references to the same list created once by list().