0

I have the following code:

def matrixReshape(mat, r, c):
    if len(mat)*len(mat[0]) != r*c:
        return mat

    nums = []
    for row in range(len(mat)):
        for col in range(len(mat[0])):
            nums.append(mat[row][col])

    res = [[0]*c]*r
    for x in range(r):
        for y in range(c):
            res[x][y] = nums.pop(0)

    return res

mat = [[1,2],[3,4]]

print(matrixReshape(mat, 4, 1))

Which results in the output:

[[4], [4], [4], [4]]

But I want it to output:

[[1], [2], [3], [4]]

I'm confused why the entire column gets updated. When I print x and y in the 2nd for loops I get: 0,0 1,0 2,0 3,0 as expected.

martineau
  • 119,623
  • 25
  • 170
  • 301
idkmath28
  • 23
  • 4

3 Answers3

2

It's because you're initializing the res variable like this:

        res = [[0]*c]*r

This makes every element in the array reference the same value. Use a list comprehension to initialize the list instead, which will copy all the elements. This is the pythonic way to initialize lists.

res = [[0 for _ in range(c)] for _ in range(r)]
jacob_g
  • 674
  • 8
  • 21
2

The problem is with the line.

res = [[0]*c]*r

When multiplying [0] with r and c, array [0] is replicated. So changing any of its instances will change a value for all.

Try the following line instead.

res = [[0 for i in range(c)] for j in range(r)]
nilbarde
  • 331
  • 1
  • 3
0

Just use simple list comprehension

[[col] for row in mat for col in row]
Vishnudev Krishnadas
  • 10,679
  • 2
  • 23
  • 55