Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What's the difference between the two list comprehension in Python?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading