Sometimes we need to reverse the order of the elements in a Python list. While there can be many different ways of implementing this task, I found three in particular that I appreciate for different reasons. Let’s define first a list of integers that we will reverse later.
|
|
List slicing
This method can be a bit obscure at first read, but basically it slices the whole list proceding in the reverse order:
|
|
Reversed method
We use the reversed method that returns an iterable object and a list comprehension to generate the new list
|
|
### Swapping values in place
This last method is more verbose and it basically divides the list in two parts and swaps the first with sixth, the second with fifth, etc…
|
|