Skip to content

Instantly share code, notes, and snippets.

@rpivo
Last active January 18, 2021 19:10
Show Gist options
  • Save rpivo/bdf0605e2c5c1650a651b52a41bef024 to your computer and use it in GitHub Desktop.
Save rpivo/bdf0605e2c5c1650a651b52a41bef024 to your computer and use it in GitHub Desktop.
Two Ways to Reverse a List in Python

Two Ways to Reverse a List in Python

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment