In this tutorial we will learn how to reverse a list in Python.
How to reverse a list in python
To reverse a list in Python, you can use the reverse()
method or the slicing technique.
Example 1 - In this we using the reverse()
method:
num_list = [1, 2, 3, 4, 5]
num_list.reverse()
print(num_list)
Output
[5, 4, 3, 2, 1]
Example 2 - In this we using the slicing technique:
num_list = [1, 2, 3, 4, 5]
num_reversed_list = num_list[::-1]
print(num_reversed_list)
Output
[5, 4, 3, 2, 1]
In the second example, we reverse the order of the components in the original list by using the [::-1] slicing syntax to generate a new list.. This slicing syntax includes all the elements up until the beginning of the list, starting at the end of the list with a step of -1.