An easy way to reverse a list in Python is to use the reverse()
list function:
l = [1, 2, 3]
l.reverse()
print(l) # [3, 2, 1]
This is nice and declarative, but reverse()
doesn't return the list. If you want to have the list implicitly returned so that you can use it in, say, a list comprehension, then using the [::-1]
syntax is better.
class Solution:
def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]:
return [[int(not bool(n)) for n in r[::-1]] for r in A]
Here's a solution to a LeetCode problem that uses the [::-1]
reversing method to immediately return the reverse list for use.
This takes A, which is a list of lists of integers, and loops through each row r
. It then takes each of these rows and gets the reverse of that row with r[::-1]
, which is immediately returned for use. It then takes each number n
from this reversed row and gets the boolean inverse of this value using int(not bool(n))
.