0

I'm trying to initialize a multi dimensional array in Python:

SIZE=3

onedimarray=[None]*SIZE

for i in range(0,SIZE):
    onedimarray[i]="{0:d}".format(i)

print(onedimarray)

multdimarray=[[None]*SIZE]*SIZE

for i in range(0,SIZE):
    for j in range(0,SIZE):
        multdimarray[i][j]="{0:d},{1:d}".format(i,j)

print(multdimarray)

This code when run prints:

['0', '1', '2']
[['2,0', '2,1', '2,2'], ['2,0', '2,1', '2,2'], ['2,0', '2,1', '2,2']]

So in the one dimensional case the * operator initialized the array correctly. In the multi dimensional case each row of the array is the same.

I'm fairly new to Python and don't understand this behavior. Can anyone explain what is going on?

sbtpr
  • 541
  • 5
  • 18
  • 3
    FYI they are lists (second one is a nested list), not arrays – DavidG Jan 05 '18 at 15:53
  • I'm trying to use Python from Node.js in order to access TensorFlow from the browser, so my thinking is determined by Javascript where there are arrays. Anyway, based on the duplicated question's title I would never have been able to find that answer. – sbtpr Jan 05 '18 at 16:02

0 Answers0