In this chapter, we shall explore the different ways to rearrange the given array in the reverse order of the index. In Python, array is not one of the built-in data types. However, Python's standard library has array module. The array class helps us to create a homogenous collection of string, integer or float types.
The syntax used for creating array is −
Let us first create an array consisting of a few objects of int type −
The array class doesn't have any built-in method to reverse array. Hence, we have to use another array. An empty array "b" is declared as follows −
Next, we traverse the numbers in array "a" in reverse order, and append each element to the "b" array −
The array "b" now holds numbers from original array in reverse order.
Example 1
Here is the complete code to reverse an array in Python −
It will produce the following output −
array('i', [10, 5, 15, 4, 6, 20, 9]) array('i', [9, 20, 6, 4, 15, 5, 10])
We can also reverse the sequence of numbers in an array using the reverse() method in list class. List is a built-in type in Python.
We have to first transfer the contents of an array to a list with tolist() method of array class −
We can call the reverse() method now −
If we now convert the list back to an array, we get the array with reversed order,
Example 2
Here is the complete code −
It will produce the following output −
array('i', [10, 5, 15, 4, 6, 20, 9])
The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.