« Search  |  Retro Site View (Experimental)  |  Switch to Reader Mode Images: 56K  |  Retro Mode: ON  |  Original Site »
www.tutorialspoint.com   (www.tutorialspoint.com · converted in 283 ms)
Sections: Tutorials point  |  Python Technologies  |  Databases  |  Computer Programming  |  Web Development  |  Java Technologies  |  Computer Science  |  Mobile Development  |  Big Data & Analytics  |  Microsoft Technologies  |  DevOps  |  Latest Technologies  |  Machine Learning  |  Digital Marketing  |  Software Quality  |  Management Tutorials

Python Array reverse() Method

Python Tutorial
Selected Reading

Python Array reverse() Method




Previous Quiz Next

The Python array reverse() method is used to reverse the order of the items in an array.

Syntax


Following is the syntax of Python array reverse() method −

array_name.reverse()

Parameters


This method does not accept any parameter.

Return Value


This method does not return any value.

Example 1


Following is the basic example of python array reverse() method −

import array as arr
#Creating an array
my_array1 = arr.array('i',[40,50,60,15,90,20])
#Printing the elements of an array
print("Original Array: ",my_array1)
#reversing the array
my_array1.reverse()
print("Reversed Array: ", my_array1)

Output

Following is the output of the above code −

Original Array:  array('i', [40, 50, 60, 15, 90, 20])
Reversed Array:  array('i', [20, 90, 15, 60, 50, 40])

Example 2


Lets understand with different datatype, Here we have created an array of double datatype.

import array as arr
#Creating an array
my_array2 = arr.array('d',[13.5,45.7,99.5,1.5,8.9,22.5])
#Printing the elements of an array
print("Original Array: ",my_array2)
#reversing the array
my_array2.reverse()
print("Reversed Array: ", my_array2)

Output

Following is the output of the above code −

Original Array:  array('d', [13.5, 45.7, 99.5, 1.5, 8.9, 22.5])
Reversed Array:  array('d', [22.5, 8.9, 1.5, 99.5, 45.7, 13.5])

Example 3


Lets try to reverse an array without using reverse() method −

import array as arr
#Creating an array
my_array3 = arr.array('i',[45,55,65,75,85,95])
#creating an empty array
rev_array=arr.array('i',[])
#Printing the elements of an original array
print("Original Array : ",my_array3)
#reversing the an array and appending into rev_array
length=len(my_array3)
for i in range(0,length):
    rev_array.append(my_array3[length-1-i])
#Updating original array[my_array3]   
my_array3=rev_array    
print("Reversed Array: ", my_array3)

Output

Original Array:  array('i', [45, 55, 65, 75, 85, 95])
Reversed Array:  array('i', [95, 85, 75, 65, 55, 45])

Example 4


In Python list is similar to array, Here we have created an array of string −

#Creating a string array
my_array4=["Apple","Bat","Cat","Dog"]
#reversing the string array
my_array4.reverse()
print(my_array4)
['Dog', 'Cat', 'Bat', 'Apple']
python_array_methods.htm
Tutorix - AI Tutor
Previous Quiz Next Advertisements