autofilling python list of lists

Viewed 51

When I create and fill a list of lists some odd behaviour pops up:

list1 = [[0,0,0],[0,0,0],[0,0,0]]
list2 = [[0]*3]*3

print('lists still look equal here:')
print(list1)
print(list2)

list1[1].pop(1)
list2[1].pop(1)

print('but not anymore:')
print(list1)
print(list2)

gives me this output:

lists look completely equal here:
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
but not anymore:
[[0, 0, 0], [0, 0], [0, 0, 0]]
[[0, 0], [0, 0], [0, 0]]

So the second list 'pops' from every little list instead of just the one I'm trying to. I wonder what causes this behaviour and if there is a more elegant way to fill indexable lists if I need a large amount of long lists instead of just these tiny ones?

2 Answers
Related