[Python] Matrix creation issue? - Discuss - LeetCode

1 min read Original article ↗

I was trying to solve this 1252. Cells with Odd Values in a Matrix problem. The logic was barely simple but the following matrix intialization made me in trouble. When I create the matrix using following my solution was not accepted:

matrix = [[0 for i in range(n)] for j in range(m)]

it was accepted. I am just wondering what is the difference between these two matrix creation.

class Solution:
    def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int:

        matrix = [[0] * n] * m
        for r, c in indices:
            
            for i in range(n):
                matrix[r][i] += 1

            for j in range(m):
                matrix[j][c] += 1

        return sum(0 if elem % 2 == 0 else 1 for row in matrix for elem in row)
        
class Solution:
    def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int:

        matrix = [[0 for i in range(n)] for j in range(m)]
        for r, c in indices:
            
            for i in range(n):
                matrix[r][i] += 1

            for j in range(m):
                matrix[j][c] += 1

        return sum(0 if elem % 2 == 0 else 1 for row in matrix for elem in row)