Reverse a list in Python
This post will discuss how to reverse a list in Python.
1. Using reversed() function
The reversed() function is a built-in function that returns a reversed iterator of items from an iterable. We can use this function to reverse a list and convert the result to a list using the list() function. For example:
|
1 2 3 |
a = [1, 2, 3, 4, 5] rev = list(reversed(a)) print(rev) # prints [5, 4, 3, 2, 1] |
2. Using list.reverse() function
The reverse() function is a built-in function of the list class that reverses the order of the items in the list and modifies the original list itself. We can use this function to reverse a list in-place by calling it on the list object. For example:
|
1 2 3 |
a = [1, 2, 3, 4, 5] a.reverse() print(a) # prints [5, 4, 3, 2, 1] |
3. Using extended slicing
The slicing technique is a way of accessing a subset of items from an iterable by specifying the start, stop, and step indices. We can use it to reverse a list by passing a negative step index. The slice object [::-1] will return a new list that are reversed from the original order in the list. The negative step index -1 means that the list elements are accessed from the end to the beginning.
|
1 2 3 |
a = [1, 2, 3, 4, 5] rev = a[::-1] print(rev) # prints [5, 4, 3, 2, 1] |
4. Using numpy module
We can also use the numpy module to reverse a list by using the numpy.flip() function, which reverses the order of elements along an axis. For example:
|
1 2 3 4 5 |
import numpy as np a = [1, 2, 3, 4, 5] rev = np.flip(a) print(rev) # prints [5 4 3 2 1] |
That’s all about reversing a list in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)