0

I'm very confused because in a for loop I'm printing an array value. However, after exiting a loop the output doesn't match what I'm printing. What's going on?

Code:

import numpy as np
from itertools import product

def boxBlur(image):

        m = len( image ) - 1
        n = len( image[1] ) - 1

        out = [ [0]* ( n - 1 ) ] * ( m - 1 )

        for i,j in product( range(1,m) , range(1,n) ):
                vals = np.array(image[i-1:i+2]).transpose()[j-1:j+2].flatten()

                I = i - 1
                J = j - 1

                out[I][J] = int( sum(vals) / 9 )

                print( "M[" + str(I) + "," + str(J) + "] = " + str(out[I][J]) ) 

        print(out)
        return out

image = [[7,4,0,1], 
         [5,6,2,2], 
         [6,10,7,8], 
         [1,4,2,0]]

boxBlur(image)

    M[0,0] = 5
    M[0,1] = 4
    M[1,0] = 4
    M[1,1] = 4
    [[4, 4], [4, 4]]
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
user1543042
  • 3,422
  • 1
  • 17
  • 31

1 Answers1

1

This is because out[0] and out[1] are the exact same instances, which is a consequence of the following:

out = [ [0]* ( n - 1 ) ] * ( m - 1 )

The repetition operator, *, repeats the same instance instead of creating copies.

You could instead accomplish what you want with a list comprehension:

out = [[0]* ( n - 1 ) for _ in range(m - 1)]
bgfvdu3w
  • 1,548
  • 1
  • 12
  • 17