Python provides multiple ways to reverse the elements in a list.
Python Reverse List Elements
The following techniques can be used to reverse a Python List:
- By using the reversed() function
- By using the reverse() function
- By using Slicing technique
- By using for loop and range() function
1. reversed() function
The reversed()
method creates a reverse iterator to traverse through the list in reverse order.
def reverse_list(input):
return [x for x in reversed(input)]
input = [0, 22, 78, 1, 45, 9]
print(reverse_list(input))
Output:
[9, 45, 1, 78, 22, 0]
2. reverse() function
The reverse()
function provides the functionality to reverse the elements and store them within the same list instead of copying the elements into another list and then reversing it.
def reverse_list(input):
input.reverse()
return input
input = [0, 22, 78, 1, 45, 9]
print(reverse_list(input))
Output:
[9, 45, 1, 78, 22, 0]
3. Slicing technique
The slicing technique
provides the functionality to reverse the list.
def reverse_list(input):
output = input[::-1]
return output
input = [0, 22, 78, 1, 45, 9]
print(reverse_list(input))
Output:
[9, 45, 1, 78, 22, 0]
4. By using for loop and range() function
input = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Get list length
list_len = len(input)
# i goes from 0 to the middle
for x in range(int(list_len/2)):
n = input[x]
input[x] = input[list_len-x-1]
input[list_len-x-1] = n
# At this point the list should be reversed
print(input)
Output:
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Conclusion
Thus, in this article, we have understood and implemented various techniques to reverse a list in Python.
References
- Python reverse list
- reverse list documentation