Python Program to Reverse an Array
reversed_array = array[::-1] or array.reverse() to reverse it in place.Examples
How to Think About It
Algorithm
Code
array = [1, 2, 3, 4, 5] reversed_array = array[::-1] print(reversed_array)
Dry Run
Let's trace the example array [1, 2, 3, 4, 5] through the code that uses slicing to reverse it.
Original array
array = [1, 2, 3, 4, 5]
Apply slicing to reverse
reversed_array = array[::-1] results in [5, 4, 3, 2, 1]
Print reversed array
Output: [5, 4, 3, 2, 1]
| Step | Array State |
|---|---|
| Initial | [1, 2, 3, 4, 5] |
| After slicing | [5, 4, 3, 2, 1] |
Why This Works
Step 1: Using slicing
The array[::-1] syntax creates a new array by reading the original array from the end to the start.
Step 2: In-place reversal
Alternatively, array.reverse() changes the original array by swapping elements from both ends moving inward.
Step 3: Output
Printing the reversed array shows the elements in the opposite order from the original.
Alternative Approaches
array = [1, 2, 3, 4, 5] array.reverse() print(array)
array = [1, 2, 3, 4, 5] reversed_array = list(reversed(array)) print(reversed_array)
Complexity: O(n) time, O(n) or O(1) space
Time Complexity
Reversing requires visiting each element once, so it takes linear time proportional to the array size.
Space Complexity
Using slicing or reversed() creates a new array, so space is O(n). Using reverse() modifies in place, so space is O(1).
Which Approach is Fastest?
In-place reversal with reverse() is fastest in space, but slicing is often simpler and more readable.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Slicing (array[::-1]) | O(n) | O(n) | When you want a new reversed array |
| In-place reverse() method | O(n) | O(1) | When you want to reverse the original array without extra space |
| reversed() function | O(n) | O(n) | When you want an iterator or a new reversed list |
array[::-1] for a quick and easy way to reverse an array without changing the original.array.reverse() changes the original array and returns None, so printing its result directly shows None.