Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python Array reverse() Method



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

Syntax

Following is the syntax of Python arrayreverse() 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 arrayreverse() method −

import array as arr#Creating an arraymy_array1 = arr.array('i',[40,50,60,15,90,20])#Printing the elements of an arrayprint("Original Array: ",my_array1)#reversing the arraymy_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 ofdouble datatype.

import array as arr#Creating an arraymy_array2 = arr.array('d',[13.5,45.7,99.5,1.5,8.9,22.5])#Printing the elements of an arrayprint("Original Array: ",my_array2)#reversing the arraymy_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 toreverse an array without using reverse() method −

import array as arr#Creating an arraymy_array3 = arr.array('i',[45,55,65,75,85,95])#creating an empty arrayrev_array=arr.array('i',[])#Printing the elements of an original arrayprint("Original Array : ",my_array3)#reversing the an array and appending into rev_arraylength=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 arraymy_array4=["Apple","Bat","Cat","Dog"]#reversing the string arraymy_array4.reverse()print(my_array4)
['Dog', 'Cat', 'Bat', 'Apple']
python_array_methods.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp