Five different ways to reverse an array in python
In python, we have some built-in methods to reverse an array it makes life easier, we can also use a slicing operator to reverse an array, or by using for-loop we can also perform the reversing the array
All the five different ways that I have mentioned below having the same time complexity of O(n)
1. Reversing the array using for loop
By using for loop we can reverse the elements in the array, how we can do it? you may get this type of question, it’s easy what we need is to just replace the elements in the array, which elements are we need to replace? By replacing the last element in the list with the first element and replacing the second element with the last second element until we reach the middle, the logic goes very simple, if we write code in python for the above logic it will look like this
array=[1,2,3,4,5,6]
for i in range(len(array)//2):
a= array[i]
array[i]=array[(len(array)-1)-i]
array[(len(array)-1)-i]=a
print(“the reversed array is:”, b)
output:
the reversed array is: [6,5,4,3,2,1]
2. Reversing the array using a built-in method(reverse)
The reverse method is a built-in method in python, it is used to reverse the items in the array
array=[1,2,3,4,5,6]
array.reverse()
print(“the reversed array is:”, array)
output:
the reversed array is: [6,5,4,3,2,1]
The time complexity for the above code is: O(n)
3. Reversing the array using a built-in method(reversed)
The main difference between reverse and reversed methods is reversed method returns an iterable object we need to convert into an iterator, using the list method, when you want to print the list, slicing operation will make your life easier
array=[1,2,3,4,5,6]
a=reversed(array)
print(“the reversed array is:”, list(a))
output:
the reversed array is: [6,5,4,3,2,1]
The time complexity for the above code is: O(n)
4. Reversing the array using the slice operator
We can easily reverse the elements in the array by using slicing, slicing an array creates a copy of the reversed list which need extra space to store the reversed array
array=[1,2,3,4,5,6]
b=array[::-1]
print(“the reversed array is:”, b)
output:
the reversed array is: [6,5,4,3,2,1]
The time complexity for the above code is: O(n)
5. Reversing the array using for loop(smart way of using a range)
Here we are reversing the elements in the array using a range method, range method produces a sequence of numbers we can customize the sequence as we want, here we are taking the sequence starting from the length of the array minus one which gives us the last element in the list until we reach the first element the python code for above logic looks like this
array=[1,2,3,4,5,6]
rev=[]
for i in range((len(array)-1),-1,-1):
re.append(array[i])
print(“the reversed array is:”, rev)
output:
the reversed array is: [6,5,4,3,2,1]
The time complexity for the above code is: O(n)