Reversing a List in Python
Given a list, the task is to reverse the order of its elements. For Example:
Input: [10, 20, 30, 40, 50]
Output: [50, 40, 30, 20, 10]
Let's see other different methods to reverse a list.
Using reverse()
reverse() method reverses the elements of the list in-place and it modify the original list without creating a new list.
a = [1, 2, 3, 4, 5]
a.reverse()
print(a)
Output
[5, 4, 3, 2, 1]
Using List Slicing
This method builds a reversed version of the list using slicing with a negative step.
a = [1, 2, 3, 4, 5]
rev = a[::-1]
print(rev)
Output
[5, 4, 3, 2, 1]
Explanation:
- a[::-1] walks through the list from end to start.
- rev holds the new reversed list while a stays unchanged.
Using reversed()
Python's built-in reversed() function is another way to reverse the list. However, reversed() returns an iterator, so it needs to be converted back into a list.
a = [1, 2, 3, 4, 5]
rev = list(reversed(a))
print(rev)
Output
[5, 4, 3, 2, 1]
Using a Loop
If we want to reverse a list manually, we can use a loop (for loop) to build a new reversed list. This method is less efficient due to repeated insertions and extra space required to store the reversed list.
a = [1, 2, 3, 4, 5]
i, j = 0, len(a) - 1
while i < j:
a[i], a[j] = a[j], a[i]
i += 1
j -= 1
print(a)
Output
[5, 4, 3, 2, 1]
Explanation:
- i starts at the beginning and j at the end.
- a[i], a[j] = a[j], a[i] swaps corresponding elements.
- Loop continues until both pointers meet.