Learnitweb

How to reverse a list in Python

For the provided list, for example [1,2,3,4,5,6,7,8,9], task is to reverse the list. The output after reversing the list should be
[9,8,7,6,5,4,3,2,1]

We’ll discuss three ways to reverse the list:

  • In-place reversal using reverse() method.
  • Slicing the list using the [::-1]
  • Creating a reversed iterator using reversed() built-in function.

1.Reverse a list using reverse() method

Python has a built-in reverse() method which you can use to in-place reverse a list. Reversing the list in-place means a new list won’t be created and the original list will be modified.

inputList = [1,2,3,4,5,6,7,8,9]
print(inputList.reverse())
print('inputList',inputList)

Output

None
inputList [9, 8, 7, 6, 5, 4, 3, 2, 1]

As you can see, inputList.reverse() printed None and original list (inputList) is modified.

Benefit of using reverse() method is that it takes less memory to reverse a list.

2. Slicing the list using the [::-1]

You can use slicing feature to reverse a list. Slicing a list with [::-1] will reverse the list. This syntax is extension to access list elements using square bracket syntax.

This syntax means slice the list from last to first element of list in reverse direction. -1 represents the reverse direction.

This way of reversing a list takes more space as the original list is not modified and a shallow copy of the original list is created.

inputList = [1,2,3,4,5,6,7,8,9]
print('reverse list:', inputList[::-1])
print('inputList',inputList)

Output

reverse list: [9, 8, 7, 6, 5, 4, 3, 2, 1]
inputList [1, 2, 3, 4, 5, 6, 7, 8, 9]

As we can see, original list is not modified when we reverse the list with slicing.

3. Reversing a list using reversed()

Using built-in reversed() method is one other way to reverse a list. This method returns a reverse iterator. We can then use this reverse iterator to get the elements of the list.

inputList = [1,2,3,4,5,6,7,8,9]
itr = reversed(inputList)

for element in itr:
    print(element)

Output

9
8
7
6
5
4
3
2
1

In this method the original list is not modified in-place. A shallow copy of the original list is also not created. Instead, we are just using the reverse iterator to print the reverse of a list.

We can use list constructor to create a reverse list with reversed() method. In this case the shallow copy of the original list is created. The syntax for the same is:
list(reversed(inputList))

inputList = [1,2,3,4,5,6,7,8,9]

l = list(reversed(inputList))
print(l)

Output

[9, 8, 7, 6, 5, 4, 3, 2, 1]