Reversing a list is a commonly used operation in Python programming. Lets look into ways of reversing the order of a list in Python:
1. Using [: : -1] list slicing trick
Python list objects have a feature called slicing and slicing a list with [::-1] creates a reversed copy.
>>mylist= [ 1, 2, 3, 4, 5 ]
>>mylist
[1, 2, 3, 4, 5]
>>mylist[::-1]
[5, 4, 3, 2, 1]
By using this trick, the reversed list takes up more memory. It creates a shallow copy of the list where the container is duplicated but not the individual list elements. The references of the original elements are reused in new copy of container, instead of duplicating the list elements themselves.
2. Using list.reverse() method
Python has a built in reverse() method which one can use to reverse the contents of the list object in-place.
>>mylist= [1, 2, 3, 4, 5 ]
>>mylist.reverse()
>>mylist
[5, 4, 3, 2, 1]
Reversing a list this way takes up less memory as compare to slicing trick, as it directly modifies the original list object instead of creating a new list and copying the existing elements to it in reverse order(as done in slicing trick).
3. Using reversed() built in function
Lastly, reversing a list using reverse iteration with built in reversed() function. Unlike the above two method, it neither creates a reverse list in-place nor a full copy of list, instead it gets a reverse iterator which can be used to cycle through the elements of list in reverse order.
>>mylist = [1, 2, 3, 4, 5]
>>for revlist in reversed(mylist):
print(revlist)
5
4
3
2
1
We iterated the elements of a list in reverse order. The original list doesn’t get modified on using reversed() function but it gives a view of all the elements of list in reverse order .
We call list() constructor on the result of reversed() function, in order to get a reversed copy of the list.
>>mylist
[1, 2, 3, 4, 5]
>>list(reversed(mylist))
[5, 4, 3, 2, 1]
The built-in function uses list constructor to keep on iterating until the reverse iterator is exhausted and all the elements fetched from iterator is placed in a new list object. We get a shallow copy of the original list.