Python Program to Reverse an Array

Write a Python Program to reverse the given Numpy Array. We can use the slicing technique with a negative value to get the Numpy Array reverse. In this example, we used the same to reverse the numeric and string arrays.

import numpy as np

orgarr = np.array([15, 20, 50, 40, 78, 99, 248])
print("Original Numeric Numpy Array Items = ", orgarr)

revarr = orgarr[::-1]
print("After Reversing Numeric Numpy Array = ", revarr)

orgstrarr = np.array(['UK', 'India', 'USA', 'Japan'])
print("Original String Numpy Array Items = ", orgstrarr)

revstrarr = orgstrarr[::-1]
print("After Reversing String Numpy Array = ", revstrarr)
Python Program to Reverse an Array

Python Program to Reverse an Array using While loop

This example uses the temporary variable to shift the numeric array items and reverse them.

import numpy as np

orgarr = np.array([14, 27, 99, 50, 65, 18, 195, 100])

j = len(orgarr) - 1
i = 0

while(i < j):
    temp = orgarr[i]
    orgarr[i] = orgarr[j]
    orgarr[j] = temp
    i += 1
    j -= 1

print(orgarr)
[100 195  18  65  50  99  27  14]

Reverse an Array Using functions

In this Numpy Array example, we created a function (def reverseArray(orgarr, number)) that reverses the array passed to it.

# using functions
import numpy as np

def reverseArray(orgarr, number) :
    j = number - 1
    i = 0
    
    while(i < j):
        temp = orgarr[i]
        orgarr[i] = orgarr[j]
        orgarr[j] = temp
        i += 1
        j -= 1


arrList = []
number = int(input("Enter the Total Array Items = "))
for i in range(1, number + 1):
    value = int(input("Enter the %d Array value = " %i))
    arrList.append(value)

orgarr = np.array(arrList)
print("Original  = ", orgarr)

reverseArray(orgarr, number) 
print("After  = ", orgarr)
Python Program to Reverse an Array using while loop and functions

Reverse array items using recursion

In this program, we created a recursive function to Reverse an Array (reverseArray(orgarr, i + 1, j – 1)) with updated values.

import numpy as np

def reverseArray(orgarr, i, j) :
   if(i < j):
        temp = orgarr[i]
        orgarr[i] = orgarr[j]
        orgarr[j] = temp
        reverseArray(orgarr, i + 1, j - 1)
        

orgarr = np.array([22, 44, 87, 538, 89, 120, 197])
print("Original Numeric Numpy Array Items = ", orgarr)

reverseArray(orgarr, 0, (len(orgarr) - 1))
print("After Reversing Numeric Numpy Array = ", orgarr)
Python Program to Reverse an Array using recursion