0

Can someone explain to me why this code (python 2.7):

k=0
img = [[0]*4]*5
for i in xrange(len(img)):
    for j in xrange(len(img[0])):
        k+=1
        img[i][j] = k
print(img)

results in this:

[[17, 18, 19, 20], 
 [17, 18, 19, 20],
 [17, 18, 19, 20],
 [17, 18, 19, 20],
 [17, 18, 19, 20]]

instead of this:

[[1, 2, 3, 4], 
 [5, 6, 7, 8],
 [9, 10, 11, 12],
 [13, 14, 15, 16],
 [17, 18, 19, 20]]

I'm not sure what I'm missing...?

Ti7mq
  • 3
  • 2

1 Answers1

1

It's this line here: img = [[0]*4]*5

Basically, you're creating a reference to the array rather than creating a new one (for the second dimension). That explains why the last row is the one duplicated throughout, as it's the last one to be iterated through.

jhpratt
  • 6,841
  • 16
  • 40
  • 50
  • Not quite following, sorry. Can you explain 'creating a reference'? – Ti7mq Nov 09 '17 at 04:13
  • The issue isn't with the editing, it's with the initialization. You'll need to use `img = [[0 for i in range(4)] for j in range(5)]`, which creates what you're expecting. – jhpratt Nov 09 '17 at 04:15