Issue 12597: List created by multiplication behaves different (original) (raw)

Next code:

def ill(row): row[1]=1 list_manual=[[0,0,0],[0,0,0],[0,0,0]] list_generated=[[0,0,0]]*3 ill(list_manual[1]) print(list_manual) ill(list_generated[1]) print(list_generated)

Will output:

[[0, 0, 0], [0, 1, 0], [0, 0, 0]] [[0, 1, 0], [0, 1, 0], [0, 1, 0]]

Is it a bug?

Hi, no it's not a bug :)

What you actually get with [[0]]*3 is a list of 3 references to the same list, [0]:

a = [[0], [0], [0]] b = [[0]]*3 for i in a: print(id(i)) ... 139807725184032 139807725300280 139807725300520 for i in b: print(id(i)) ... 139807725324016 139807725324016 139807725324016