DEV Community

Jarvish John
Jarvish John

Posted on • Edited on

CA 05 - Reverse The Array

Problem Statement

Reverse an array. Reversing an array means the elements such that the element becomes the last, the second element becomes the second last, and so on.

arr[] = [1, 4, 3, 2, 6, 5]
[5, 6, 2, 3, 4, 1]

The first element moves to last position, the second element moves to second-last and so on.

arr[] = [4, 5, 1, 2]
[2, 1, 5, 4]

The first element moves to last position, the second element moves to second last and so on.

My Goal

My goal for this problem was to understand array reversal in the simplest and most efficient way possible using Python.

I wanted a clean and minimal solution which uses Python features to simplify logic. Importantly I wanted the code to be faster implementation without manual swapping.

Solution

Instead of manually swapping elements, I used Python’s slicing feature. Python allows reversing a list using slicing with [::-1].
: means full list
-1 step backwards. This directly gives the reversed array in one line.

Solution Code

a = [1, 4, 3, 2, 6, 5]

a = a[::-1]

print(a)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)