![]() |
VOOZH | about |
Given a list, the task is to reverse the order of its elements. Example:
Input: [10, 20, 30, 40, 50]
Output: [50, 40, 30, 20, 10]
Let's see different methods to reverse a list.
reverse() method reverses the elements of the list in-place and it modifies the original list without creating a new list.
[5, 4, 3, 2, 1]
This method builds a reversed version of the list using slicing with a negative step.
[5, 4, 3, 2, 1]
Explanation:
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.
[5, 4, 3, 2, 1]
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.
[5, 4, 3, 2, 1]
Explanation: