Reverse Array In Python

An array is a collection of items stored together in sequential memory locations. The idea is to store multiple items of the same type together.

image.png

So there are three ways we can reverse an array in python,

1. Slicing

We can use slicing to turn any normal list array into a reverse list array.

list = [1,2,3,4]
print(list[::-1])
Result: 4,3,2,1

How does slicing work?

Slicing has three values start stop and step which makes it easier for us to reverse the list here. Some of the examples for slicing would be:

list[start:stop]  # items start through stop -1
list[start:]      # items start through the rest of the array
list[:stop]       # items from the beginning through stop -1
list[:]           # a copy of the whole array
list[start:stop:step] # start through not past stop, by step

To make it easier we can look at this diagram below where positive values mean sequential increment and negative values mean the complete opposite.

image.png

As you can see we only used step here list[::-1] in our code to reverse the array and that is because this step works with items from first to last and the amount you put are the steps it will take, for example, if we put this list[::2] it will print only 1 and 3 because the step started from 1 and then skipped 1 and 2 and found 3 so it shows 1 and 3!

Now if you put this list[::1] it will show the all 1,2,3,4 because it is taking 1 and then taking one step and finding 2 then again another step finding 3 this way it will continue.

So now if we list[::-1] put this it goes to the last items and starts from there so the whole list gets reversed!

2. Reverse()

Python has a built-in method reverse() that automatically reverses the order of the list arrays right at the original place.

list = [1,2,3,4] 
print(list)
list.reverse()
Result: 4,3,2,1

3. Reversed()

Another similar method is there which is reversed() when passed with a list returns an iterable in reverse order.

arr_list = [1,2,3,4] 
print(list(reversed(arr_list)))
Result: 4,3,2,1