-1

The solution that is working for me for this problem (https://leetcode.com/problems/flipping-an-image/) here is

class Solution:
    def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
        return [[bit ^ 1 for bit in reversed(row)] for row in image]

However , and I feel like I dont understand something about list comprehension here, the following gives me an error:

class Solution:
    def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
        return [[bit ^ 1] for bit in reversed(row) for row in image]
        

enter image description here

Why am i getting this error ?, and similarly this does not work either.

class Solution:
    def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
        return [bit ^ 1 for bit in reversed(row) for row in image]
        
BigD
  • 75
  • 5
  • Attempts 2 and 3 need to flip the `for` loops: `[bit ^ 1 for row in image for bit in reversed(row)]` and the behavior is going to be different, flattening the 2d list. Version 2 doesn't make much sense, you'll get a list of 1-element sublists. Please see [Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question) – ggorlen Aug 18 '21 at 01:10
  • [This thread](https://stackoverflow.com/questions/18551458/how-to-frame-two-for-loops-in-list-comprehension-python) has some good explanations of list comprehensions with multiple for loops. – sj95126 Aug 18 '21 at 01:12
  • Does this answer your question? [How to make a flat list out of a list of lists](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-a-list-of-lists) – ggorlen Aug 18 '21 at 01:17

1 Answers1

0

Check [Python.Docs]: Data Structures - Nested List Comprehensions, it contains an example similar to yours.

The rules (they scale indefinitely) that need to be remembered about comprehensions evaluation:

  1. Nested: from outer to inner
  2. Plain: from left to right
>>> l0 = [[1, 2, 3], [4, 5, 6]]
>>> 
>>> [[i ** 2 for i in l1] for l1 in l0]  # Nested
[[1, 4, 9], [16, 25, 36]]
>>> 
>>> [[i ** 2] for l1 in l0 for i in l1]  # Plain (notice the (reversed) for order)
[[1], [4], [9], [16], [25], [36]]

In the example above:

  • Nested: Identifiers in the outer scope are visible in the inner one(s): l1
  • Plain: Identifiers must exist before being referenced: l1 before i
CristiFati
  • 38,250
  • 9
  • 50
  • 87