I just solved a question in LeetCode, however I found that the two different list comprehensions produce different results. So what’s the difference?
ans = [ * (n-2)] * (n-2)
ans = [ * (n-2) for _ in range(n-2)]
The question is LeetCode 2373, and the two different results are as follows:
This solution gives the wrong answer because of the list comprehension
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: n = len(grid) ans = [ * (n-2)] * (n-2) print(ans) for i in range(n-2): for j in range(n-2): ans[i][j] = max(grid[x][y] for x in range(i, i+3) for y in range(j, j+3)) return ans
[expression] * n evaluates
expression once, so you’ll get a list with n occurrences of the same value (and as Iain Shelvington pointed out, this is not a list comprehension).
[expression for element in source] reevaluates
expression for every
element in the
source (and this is a list comprehension).
In your situation, this means that the first version will produce a list where each element is the same list of zeroes, so if you set an element in one of the inner lists, you’ll actually set it in all the inner lists.