Are you finding it complex to reverse an array in Python? If yes, then follow these easy steps on how to reverse an array Python in 2023 and make it quite handy for you.
In many languages like Java, C, C++ etc. there is a built-in data structure known as Array. Arrays are continuous collection of data with a fixed size. Python does not have a inbuilt array data structure, instead it has lists.
While lists and arrays may appear similar to each other, they are quite different from each other. The biggest difference between an array and a list is that arrays have fixed size, whereas the size of a list can be changed after definition.
Also, arrays can have elements of only one data type, unlike lists which can contain elements of multiple types.
Before we learn how to reverse an array Python, first we should understand what is an array and how does it work in python.
Arrays in Python
So if python does not have inbuilt arrays, how do we declare one ? Well, we can import the array module and declare and use arrays with the help of it.
The array function of the array module requires the data-type of the array elements and the size of array as arguments and declares an array of the given size and type.
Example:
import array as a
#initializing array with integers
arr = a.array('i', [5, 6, 7, 4, 3])
print('The array is: ',arr)
Output:
The array is: array(‘i’, [5, 6, 7, 4, 3])
What is meant by Array Reversal ?
Reversing an array is a very frequently needed task that we may need to perform. Array reversal, as the name suggests, refers to reversing the order of the array elements. For example
[3, 4, 5, 2] => [2, 5, 4, 3]
Reversing an array is required in many algorithms. For example:
- checking if the given number or string is a palindrome(meaning it is same when written forwards as well as backwards.
- Separating the digits of a number, etc.
How to Reverse an Array Python
There are many ways to reverse an array python. Let’s discuss them one by one
By Swapping the Elements
It is one of the common methods of reverse an array Python. This method involves iterating over the array from the starting index to half its length, swapping the corresponding from start and end in each iteration.
Example:
import array as a
arr = a.array("i", [5, 6, 7, 4, 3])
print("The original array is : ", arr)
l = len(arr)
for i in range(l // 2):
  arr[i], arr[l - i - 1] = arr[l - i - 1], arr[i]
print("The reversed array is : ", arr)
Output:
The original array is : array(‘i’, [5, 6, 7, 4, 3])
The reversed array is : array(‘i’, [3, 4, 7, 6, 5])
By using reversed() method
We know python is famous for its abundance of pre-defined modules and methods to facilitate frequently done tasks, the reversed() method is no exception.
The reversed() function takes the original array as parameter and returns an iterator for traversing the array backwards. This means that neither the reversed() method reverses the array, nor does it return a new array with reversed elements.
Example:
import array as a
arr = a.array("i", [5, 6, 7, 4, 3])
print("The original array is : ", arr)
iter = reversed(arr)
print("The reversed array is : ", iter)
Output:
The original array is : array( ‘i’, [5, 6, 7, 4, 3] )
The reversed array is : <reversed object at 0x7f0132c5d4c0>
The iterator in itself cannot give us the reversed array. But, when we convert the iterator to a list, it returns a list containing the array elements but in reverse order.
Example:
import array as a
arr = a.array("i", [5, 6, 7, 4, 3])
print("The original array is : ", arr)
rev_list = list(reversed(arr))
print("The reversed array is : ", rev_list)
Output:
The original array is : array(‘i’, [5, 6, 7, 4, 3])
The reversed array is : [3, 4, 7, 6, 5]
By using reverse() method
The reverse() method works similar to the swapping method that we discussed earlier. It works on the original and converts the array into an array with the elements in reverse order than before.
Example:
import array as a
arr = a.array("i", [5, 6, 7, 4, 3])
print("The original array is : ", arr)
a.reverse()
print("The reversed array is : ", arr)
Output:
The original array is : array(‘i’, [5, 6, 7, 4, 3])
The reversed array is : array(‘i’, [3, 4, 7, 6, 5])
While the reverse() and reversed() methods might feel to give the same results, they are very different in their working. The reverse() method changes the original array, without using any extra space, the reversed() method requires separate memory for the reversed array and the original array remains intact.
By using Recursion
Recursion is one of the most complex methods to reverse an array Python. Recursion can be considered one of the most useful ways of writing code. What is recursion you ask ?
When a function calls itself during its execution, it is called recursion.
When any variable, function or class is declared in a program, it is stored in the call stack. A stack is basically a data structure in which the last element to go in is the first one to come out.
When a function makes recursive calls, the calls keep on adding up to the call stack until a base condition is hit. The base condition is a condition which tells the function when to stop the recursion.
The functions then start returning the return values to the previous function which called them and the whole execution completes in this manner.
One needs to be extra careful while using recursion. If the base condition of a recursion is not written properly, and it fails to stop the recursion, the function will keep calling itself until the call stack overflows. This may lead to crashing of the program.
So how do we use recursion to reverse an array. We remove the first element of the array and keep on calling the function for the remaining array till the length of the array remains 1.
After this, we keep on adding the earlier removed element to the back of the array and return it to the previous call. The code explanation is given below.
Example:
import array
#function to reverse array
def reverseArray(arr):
if len(arr) == 1:
return arr
#print(arr) ->You can uncomment this to know how recursion works
return reverseArray(arr[1:]) + arr[0:1]
#declaring array
a = array.array('i', [5, 6, 7, 4, 3])
print("The original array: ", a)
print('The reversed array is: ',reverseArray(a))
Output:
The original array is : array(‘i’, [5, 6, 7, 4, 3])
The reversed array is : array(‘i’, [3, 4, 7, 6, 5])
By Slicing (Most Used)
This is one of the widely uses method to reverse an array Python. Slicing is one of the most convenient and useful operation when it comes to lists and arrays.
When reversing an array using slicing, it does not change the original array, instead a copy of the array is returned with the elements in reverse order. And this is done without using any extra memory space. The syntax for slicing is as follows:
array_name[start : end : step]
The terms used in the above syntax are:
- Start: specifies the position from which the array traversal should be started.(default : 0)
- End: specifies the position where the traversal should end. (default : length of array – 1 )
- Step: specifies how many elements to jump while traversing.(default : next element : 1)
Now, we know that the indices of an array start from 0 and go to 1 less than the no. of elements in it. But what if we give negative integers as index. The indexing of an array with negative integers has -1 for the last element and then decreases as we come to the start of the array.
This behaviour can be used for array reversal. In fact, this is the most used method for array reversal.
For the reversal, the slicing will be done as : arr[::-1]
This slicing denotes that when we start at index 0, we deduct 1 from it, making the starting index -1, then we consecutively keep on going backwards in the array until we have traversed all the array elements.
What we are doing here is reverse traversal of array and not array reversal. This means that we are not actually reversing the array, we are just traversing the array backwards to make it look like the array has been reversed.
Example:
import array as a
arr = a.array("i", [5, 6, 7, 4, 3])
print("The original array is : ", arr)
print('The reversed array is ', a[::-1])
Output:
The original array is : array(‘i’, [5, 6, 7, 4, 3])
The reversed array is : array(‘i’, [3, 4, 7, 6, 5])
Conclusion
This is all about reverse an array Python. Reversing an array is a very frequently encountered task in programming. Whether it is to solve competitive coding questions or doing actual array manipulations in a program, array reversal is a must to know for a programmer.
Each of the above shown methods has its own pros and cons. Reverse() and reversed() are the easiest to implement while slicing method is faster as it is only traversing in backward direction without actually reversing the elements.
The choice should be made according to the nature of the problem needed to be solved and thus, we must keep learning new ways to solve a problem. If you think that we have missed any detail on how to reverse an array Python then comment down below