-1

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 = [[0] * (n-2)] * (n-2)
ans = [[0] * (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 = [[0] * (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
Dog Fish
  • 13
  • 3
  • 1
    The first example is not a list comprehension. Does this answer your question https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly? – Iain Shelvington Mar 01 '23 at 15:27
  • Try `print([id(v) for v in ans])` for both cases. In the first, you'll notice that python expanded the outer list list with multiple references to a single inner list in the first example but created new lists in the second example. – tdelaney Mar 01 '23 at 15:31

1 Answers1

0

[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.

Aasmund Eldhuset
  • 37,289
  • 4
  • 68
  • 81
  • oh thanks, I should have noticed that. – Dog Fish Mar 01 '23 at 15:35
  • @DogFish: It's a common Python trapdoor (and a badly designed aspect of the language, IMO, since it's usually not what you want). Even something as simple as `[[]] * n` in an attempt to get _n_ empty lists suffers from the same effect, where all the empty inner lists are the same. However, you've also discovered the proper solution, which is to use a list comprehension, which in this simpler example would be `[[] for _ in range(n)]`. – Aasmund Eldhuset Mar 01 '23 at 15:39