2 different ways to initialise a 2d list give different results

I was initialising a 2d list and was getting strange results.
After some furtling around I found that the way I was initialising the list had an unexpected impact.

rows =2
columns= 2
mylist = [[0 for x in range(columns)] for x in range(rows)]
print (Array)
print (type(Array))
print (type(Array[0]))
print (type(Array[0][0]))
print (mylist)
print (type(mylist))
print (type(mylist[0]))
print (type(mylist[0][0]))
for i in range(rows):
    for j in range(columns):
        Array[i][j] = '%s,%s,%s'%(i,j,x)
        mylist[i][j] = '%s,%s,%s'%(i,j,x)
print (Array)
print (mylist)

Gives output:

[[0, 0], [0, 0]]
<class 'list'>
<class 'list'>
<class 'int'>
[[0, 0], [0, 0]]
<class 'list'>
<class 'list'>
<class 'int'>
[['1,0,3', '1,1,4'], ['1,0,3', '1,1,4']]
[['0,0,1', '0,1,2'], ['1,0,3', '1,1,4']]

I am a bit puzzled by this. It seems both outer list entries for the Array are being treated as the same object. Any explanation would be welcome.

Python works with references. It won’t copy objects unless you do so explicitly. When you multiply a list, you’re not duplicating objects, you’re duplicating references to objects.

1 Like

That worked. The site I read that showed initialising a 2d array with


without mentioning this gotcha was obviously incomplete.

Thanks for the help.