Python Program to Reverse a List
reversed_list = original_list[::-1] or by using the reverse() method like original_list.reverse().Examples
How to Think About It
Algorithm
Code
original_list = [1, 2, 3, 4, 5] reversed_list = original_list[::-1] print(reversed_list)
Dry Run
Let's trace reversing the list [1, 2, 3, 4, 5] using slicing.
Original list
original_list = [1, 2, 3, 4, 5]
Apply slicing with step -1
reversed_list = original_list[::-1] results in [5, 4, 3, 2, 1]
Print reversed list
Output: [5, 4, 3, 2, 1]
| Index | Value |
|---|---|
| 4 | 5 |
| 3 | 4 |
| 2 | 3 |
| 1 | 2 |
| 0 | 1 |
Why This Works
Step 1: Using slicing
The slicing syntax list[::-1] reads the list from the end to the start, creating a new reversed list.
Step 2: Using reverse() method
The reverse() method changes the original list by swapping elements from front and back until the middle is reached.
Alternative Approaches
original_list = [1, 2, 3, 4, 5] original_list.reverse() print(original_list)
original_list = [1, 2, 3, 4, 5] reversed_list = [] for item in original_list: reversed_list.insert(0, item) print(reversed_list)
Complexity: O(n) time, O(n) space
Time Complexity
Reversing a list requires visiting each element once, so it takes linear time proportional to the list size.
Space Complexity
Using slicing creates a new list, so it uses extra space proportional to the list size. The reverse() method works in place using constant extra space.
Which Approach is Fastest?
The reverse() method is fastest and uses less memory because it reverses the list in place. Slicing is simpler but uses extra memory.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Slicing (list[::-1]) | O(n) | O(n) | When you want a new reversed list |
| reverse() method | O(n) | O(1) | When you want to reverse the list in place |
| For loop with insert | O(n²) | O(n) | Learning purpose, less efficient |
list[::-1] for a quick and easy way to reverse a list without changing the original.list.reverse() to a variable, but it returns None because it reverses in place.