Reverse an array in Python
In this post, you will learn how to reverse an array using the Python programming language. There are different ways to reverse an array in Python. Here, we have mentioned most of them.
- Reversing an Array List in Python
- Reversing an Array of Array Module in Python
- Reversing a NumPy Array in Python
Reversing an Array List in Python
The most commonly used data structures in Python are an array and a list. An array is a container that can hold a fixed number of items, and these items should be of the same type.
Using List Slicing to Reverse an Array in Python
List slicing refers to accessing a specific portion or a subset of the list for some operation while the original list remains unaffected. We can also use the slicing operator to reverse a list. For this, we use the "[::-1]" list slicing trick to create a reversed copy. The following example demonstrates this-
# Initializing an array
house_items = ['chair','table','bed','pillow','towel']
print('Original Array:', house_items )
# Reversing a list
reversed_array = house_items [::-1]
# reversed list
print(Reversed Array:', reversed_array)
Output of the above code:
Original Array: ['chair', 'table', 'bed', 'pillow', 'towel']
Reversed Array: ['towel', 'pillow', 'bed', 'table', 'chair']
Using reverse() method to Reverse an Array in Python
In the given example, we have used the reverse() method to reverse the elements of the list. This method doesn't return any value. It updates the existing list.
# initialize an array
food_menu = ['Pizza','Burger','Potato Wrap','Sandwich','Chowmein']
print('Original Array:', food_menu)
# reversing array
food_menu.reverse()
# reversed array
print('Reversed Array:', food_menu)
Output of the above code:
Original Array: ['Pizza', 'Burger', 'Potato Wrap', 'Sandwich', 'Chowmein']
Reversed Array: ['Chowmein', 'Sandwich', 'Potato Wrap', 'Burger', 'Pizza']
Using reversed() Method to Reverse an Array in Python
The reversed() method is an in-built method of the Python to create a reversed order of the list. It returns the reversed iterator of the given sequence-
# Initializing an array
student_names = ["Henry", "Smith", "Priska", "John"]
print('Original Array:', student_names)
# Reversing an array
print("Reversed Array: \n")
for x in reversed(student_names):
print(x)
Output of the above code:
Original Array: ['Henry', 'Smith', 'Priska', 'John']
Reversed Array:
John
Priska
Smith
Henry
Reversing an Array of Array Module in Python
Array can be handled in Python by a module named array. The array module defines an object type that can compactly represent an array of some basic values such as characters, integers, and floating-point numbers.
Using reverse() method to reverse an array in Python
The reverse() method can also be used to reverse an array in Python of the Array module. It reverses an array to its original location. It doesn't require extra space for storing the results, as it reverses an array at its original location.
import array
# Original array
arr = array.array('i',[43, 65, 64, 23, 44, 21, 12])
print("Original Array:")
for i in range (0, 7):
print (arr[i], end =" ")
print()
# Reversing array
arr.reverse()
print("Reversed Array:")
for i in range (0, 7):
print (arr[i], end =" ")
print()
Output of the above code:
Original Array:
43 65 64 23 44 21 12
Reversed Array:
12 21 44 23 64 65 43
Using reversed() method to reverse an array in Python
We can also use the reversed() method to reverse an array in Python of the Array module.
import array
# Original array
arr = array.array('i',[67, 32, 12, 55, 34, 22, 12])
print("Original Array:")
for i in range (0, 7):
print (arr[i], end =" ")
print()
# Reversing array
res_arr=array.array('i',reversed(arr))
print("Reversed Array:")
for i in range (0, 7):
print (res_arr[i], end =" ")
print()
Output of the above code:
Original Array:
67 32 12 55 34 22 12
Reversed Array:
12 22 34 55 12 32 67
Reversing a NumPy Array in Python
The Python NumPy module provides array() function to create the numpy array. This function accepts lists of element values inside square brackets. Using this method, we can easily create a single or multi-dimensional array. We can also specify the data type of the array elements.
Using flip() Method
The flip() method in the NumPy module reverses the order of a NumPy array and returns the NumPy array object. It accepts the array and axis as arguments and returns the array while preserving the shape of the array.
import numpy as np
# Original array
nparr = np.array(['Priska','Kashyap','Girish','Somya','Smith',])
print("Original Array:")
print(nparr)
# Reversing array
print("Reversed Array:")
res_arr=np.flip(nparr)
print(res_arr)
Output of the above code:
Original Array:
['Priska' 'Kashyap' 'Girish' 'Somya' 'Smith']
Reversed Array:
['Smith' 'Somya' 'Girish' 'Kashyap' 'Priska']
Using flipud() Method
The np.flipud() is a numpy library function that is used to flip a given array in the up/down direction. The numpy.flipud() returns a view. Because a view shares memory with the original array, changing one value changes the other.
import numpy as np
# Original array
nparr = np.array(['Dog','Cat','Rat','Cow','Goat','Rabbit'])
print("Original Array:")
print(nparr)
# Reversing array
print("Reversed Array:")
res_arr=np.flipud(nparr)
print(res_arr)
Output of the above code:
Original Array:
['Dog' 'Cat' 'Rat' 'Cow' 'Goat' 'Rabbit']
Reversed Array:
['Rabbit' 'Goat' 'Cow' 'Rat' 'Cat' 'Dog']
Using Simple Slicing
We can also use a simple slicing process to reverse a numpy array. The following example demonstrates this-
import numpy as np
# Original array
nparr = np.array(['black','red','yellow','grey','pink'])
print("Original Array:")
print(nparr)
# Reversing array
print("Reversed Array:")
res_arr=nparr[::-1]
print(res_arr)
Output of the above code:
Original Array:
['black' 'red' 'yellow' 'grey' 'pink']
Reversed Array:
['pink' 'grey' 'yellow' 'red' 'black']
Related Articles
Alphabetical order Python
Write a program to read two numbers and print their quotient and remainder in python
ASCII value in Python
Greatest common divisor (GCD) in Python
Python nonlocal keyword
Prime factor Python
casefold in Python
strip function in Python
Vader Sentiment Analysis Python
isalpha Python
Python YouTube Downloader Script
Python project ideas for beginners
Pandas string to datetime
Fillna Pandas Example
Lemmatization nltk
How to generate QR Code in Python using PyQRCode
OpenCV and OCR Python
PHP code to send SMS to mobile from website
Fibonacci Series Program in Python
Python File Handler - Create, Read, Write, Access, Lock File
Python convert XML to JSON
Python convert xml to dict
Python convert dict to xml