89DEVs

Python: How to reverse a list?

How to reverse a list in Python?

To reverse a list in Python, choose between one of the following three options.
  1. slice notations
  2. reverse()
  3. reversed()

reverse a list using slice notations

Use the slice notation for stepping backward one by one: [::-1] # reverse a list using slice notations myList = [3, 2, 1] myReversedList = myList[::-1] print(myReversedList) The list is reversed by the slice notation and printed. [1, 2, 3]

reverse a list using reverse()

In Python, the list object has a reverse() method to reverse the object. # reverse a list using reverse() myList = [3, 2, 1] myList.reverse() print(myList) The list is reversed and then printed. [1, 2, 3]

reverse a list using reversed()

The reversed() function returns a list_reverseiterator object. # reverse a list using reversed() myList = [3, 2, 1] # reverse the list myReversedList = reversed(myList) # turn the list_reverseiterator object into a list myList = list(myReversedList) # print the list print(myList) The list is reversed by the reversed() function, which returns a list_reverseiterator object. Then list() is used to turn it into a list again. [1, 2, 3]

                
        

Summary


Click to jump to section