I'm sure this has been answered somewhere but I wasn't sure how to describe it.
Let's say I want to create a list containing 3 empty lists, like so:
lst = [[], [], []]
I thought I was being all clever by doing this:
lst = [[]] * 3
But I discovered, after debugging some weird behavior, that this caused an append update to one sublist, say lst[0].append(3)
, to update the entire list, making it [[3], [3], [3]]
rather than [[3], [], []]
.
However, if I initialize the list with
lst = [[] for i in range(3)]
then doing lst[1].append(5)
gives the expected [[], [5], []]
My question is why does this happen? It is interesting to note that if I do
lst = [[]]*3
lst[0] = [5]
lst[0].append(3)
then the 'linkage' of cell 0 is broken and I get [[5,3],[],[]]
, but lst[1].append(0)
still causes [[5,3],[0],[0]
.
My best guess is that using multiplication in the form [[]]*x
causes Python to store a reference to a single cell...?