How To Use Python Reverse Array With Example?

Python Reverse Array

Share:

Introduction

Python reverse array is an essential technique in programming with arrays. Arrays are data structures that hold a string of similar data. You can do certain operations on the arrays to make the program give the desired output. Python reverse array is one such function. In this tutorial, we will learn some methods to reverse an array in Python. 

Arrays are an important data structure, and Python uses them as containers to store collections of similar data types, saving itself space and time. Python does not have any support for the array data structure. It uses Python Lists to do operations on the Arrays. To use typical arrays, we can import modules such as Array or NumPy. 

Related Post: Tutorial: How to Use Python Delete File?

Since we are familiar with the topic, let’s start the tutorial.  

Python Reverse List Array

How do you reverse an array in Python? As I said, Python doesn’t have an in-built Array data structure. But it has Lists. 

Lists is an important built-in data type in Python used to store data. A big difference between a list and an array is that array is a collection of the same data type, while list allows different data types. Python does not support Arrays; hence we use lists to depict the arrays and do all their functions. Let us look at some methods for Python Reverse List as Arrays.

1. Reverse List Python Slicing

We can do Python reverse array via a list using a method called slicing. In slicing, we create a new list in reverse order by indexing the starting point, end point, and the values to be jumped. Mostly we reverse the full string so we only fill the value we want to jump. You can jump to the Python Reverse String heading below to learn more. 

 Reverse List Python Slicing Example

#The original array
arr = [1, 2, 3, 4, 5]
print("Array is :",arr)
res = arr[::-1] #reversing using list slicing
print("Reversed array:",res)

Output:

Array is : [1, 2, 3, 4, 5]
Reversed array: [5, 4, 3, 2, 1]

To know more about Python Reverse List function, read this blog:

2. Using reverse() Method

Python has a built-in method called reverse() function to Python reverse array. This function directly reverses the order of list items from the place. It changes the order of the actual list so that the original order will be gone.

Python Reverse Array Using reverse() Method Example

arr = [1, 2, 3, 4, 5]
print("Original Array :",arr)
arr.reverse() #reversing using reverse()
print("Reversed Array:",arr)

Output:

Original Array is : [1, 2, 3, 4, 5]
Reversed Array: [5, 4, 3, 2, 1]

3. Using reversed() Method

If you need the original list even after the reversal, we have another method to the Python reverse array; reversed() function. When we pass this function with a list, it returns an iterable that contains the items in the original list in reverse. Using the list() method on the iterable will result in a new list of the reversed array.

Python Reverse Array Using reversed() Method Example

#The original array
arr = [1, 2, 3, 4, 5]
print("Original Array:",arr)
#reversing using reversed()
result=list(reversed(arr))
print("Reversed Array:",result)

Output:

Original Array: [1, 2, 3, 4, 5]
Reversed Array: [5, 4, 3, 2, 1]

Python Reverse Array Using Array Module

Another method for Python Reverse Array is to use the Array module. Python uses this module to create array-like objects. However, this module has a lot of restrictions regarding the array’s data types, including restrictions by Typecode. But it is a widely used module for working with Array data structures in Python. 

Syntax- 

class array.array(typecode[,initializer])

Now let us learn how to reverse an array using this Array module –

1. Reverse Array Module Using reverse() Method

This function is similar to lists, the reverse() function directly reverses an array module in Python. It doesn’t require any extra space for storing results and it reverses the array at its original location.

Python Reverse Array Module Using reverse() Method Example

import array
#The original array
new_arr=array.array('i',[1, 2, 3, 4, 5])
print("Original Array:",new_arr)
#reversing using reverse()
new_arr.reverse()
print("Reversed Array:",new_arr)

Output:

Original Array: array('i', [1,2,3,4,5])
Reversed Array: array('i', [5,4,3,2,1])

2. Reverse Array Module Using reversed() Method

This one is again same as the list method. Now let’s reverse the  Array module with reversed() function. 

Python Reverse Array Module Using reversed() Method Example

import array
#The original array
new_arr=array.array('i',[1,2,3,4, 5])
print("Original Array:",new_arr)
#reversing using reversed()
res_arr=array.array('i',reversed(new_arr))
print("Resultant Reversed Array:",res_arr)

Output:

Original Array: array('i', [1,2,3,4,5])
Reversed Array: array('i', [5,4,3,2,1])

Python reverse Numpy Array

Let’s get on to the Numpy reverse array module now. Numpy method allows us to use array data structures of similar data types really fast in Python.

Syntax:

numpy.array(object, dtype=None, *, copy=True, order=’K’, subok=False, ndmin=0, like=None)

Parameters:

Objectarray_like: The array or any object that returns an array. If the object is a scalar quantity, a 0-dimensional array is returned.

dtypedata-type (optional): The data-type of the array. If you don’t provide it, then the minimum data type required to hold the objects will be created itself.  

Copybool (optional): It is a boolean function. The default is true meaning the object is copied. If false, copy will be made if __array__ returns a copy as per the requirements.

order{‘K’, ‘A’, ‘C’, ‘F’} (optional): To specify the array layout. C order means array in row major and F order means array in Column major.   

Subokbool (optional): Another Boolean function. True- Will pass through the sub-classes. If not, the returned array will by default become a base-class array.

Ndminint (optional): Use it if you want to specify the minimum dimension required in the resulting array.

likearray_like (optional): Used to create arrays that are not NumPy arrays. It is a reference object that creates array objects that are compatible with the array passed in the argument. 

Related Post: How to Use Python Sum Function with Examples?

Let’s now code some Python return array programs with Numpy reverse array. 

1. Python reverse Numpy Array Using flip() Method

For Python reverse array, the flip() method comes handy. In NumPy reverse array module, the function flips the order of a NumPy array, reversing it and returning the NumPy array object.

Syntax:

numpy.flip(m, axis=None)

Parameters:

mInput array

Axis: The Axis along which array is to flip over. The default axis=None.

Python reverse Numpy Array Using flip() Method Example

a) For 1D Array

import numpy as np
#The original NumPy array
new_arr=np.array([1, 2, 3, 4, 5])
print("Original Array:",new_arr)
#reversing using flip() Method
res_arr=np.flip(new_arr)
print("Reversed Array:",res_arr)

Output:

Original Array: [1, 2, 3, 4, 5]
Reversed Array: [5, 4, 3, 2, 1]

b) For 2-D array

arr = np.array([[9 8 7],[6 5 4],[3 2 1]])
# Use numpy flip() function with 2-d arrays
arr2 = np.flip(arr)
print(arr2)

Output

[[1,2,3]
[4,5,6]
[7,8,9]]

2. Python reverse Numpy Array Using flipud() Method

Another method for Python reverse array is the flipud() method. In the NumPy reverse array function, it flips an array up/down. Let’s use it in an example.

Python reverse Numpy Array Using flipud() Method Example

import numpy as np
#The original NumPy array
new_arr=np.array([1,2,3,4,5])
print("Original Array:",new_arr)
#reversing using flipud() Method
res_arr=np.flipud(new_arr)
print("Reversed Array:",res_arr)

Output:

Original Array: [1,2,3,4,5]
Reversed Array: [5,4,3,2,1]

Python Reverse String

Just like arrays, Python does not contain any built-in function to reverse a String. The best way to do it is to use a slice that treads steps backwards, -1.

Python Reverse String Example:

Reverse the string: “Hire Python Developers”

To Python reverse string, we create a slice that starts from one of the end of the string and then moves backwards.

Syntax of Slice is [x:y:z] where, 

x= start of the string
y= end of string
z= value jumped.

The slice [::-1] means

x= it will start at the end of string
y= end at position 0
z= tread a step backwards -1

Program: 

txt = "Hire Python Developers"[::-1]
print(txt)

Output: 

srepoleveD nohtyP eriH

Conclusion

Python reverse array is an important method and in this tutorial we learned about different ways to reverse arrays in Python. We hope this tutorial gave you some clarity about the concept. If you want to hire Python developers for your project contact us.

0

Share:

Subscribe for newsletter

Trusted By

Our platform focuses on making the remote hiring process easier by providing top quality vetted developers from around the world. Through our service many well-known companies have scaled their product development team.

Related Article

Ready to scale your team with remote engineers?