Revering the list is a popular interview question, especially in Python. Maybe because there are couple of ways to do it easy using Python built-in functions.
Let's say we have a list of numbers:
ar = [ 1,2,3,4,5,6]
[6,5,4,3,2,1]
A very common approach is using Python slicing. The slicing format is [start : stop : step ], so in our case we want to start from last to first, moving backward one step at a time:
ar[::-1]
The second approach is using list built in reverse function, this function will reverse the element in place.
ar.reverse()
Other approach is using build in reversed function, which will generate reverse iterator to access the elements in reverse order.
list(reversed(ar))
Summary:
Depends on the size of the list and memory constraints, we may choose one approach vs other.
Slicing is returning a new list, not very memory efficient. It also computes the reverse of the entire list and return the result.
built-in list reverse() function, will change the order in place. Thus, no more extra memory is needed, but still it will calculate the entire reversed list.
the reversed() function will pass an iterator, which leverage lazy computation. So it will calculate the next reversed element when needed. It has lazy computation benefits, which is great if we are dealing with a huge list.
Comments