Python Arrays Example

In this tutorial, we will learn about how to declare an array, its methods and attributes along with the working examples of it.

Arrays Examples:

The arrays class of arrays module in Python offers methods to process the arrays easily. The programmers can easily perform certain operations by using these methods. We should understand that a method is similar to a function that performs a specific task. But methods are written inside a class whereas a function can be written inside or outside the class. Methods are generally called as: objectname.method(). Please see Table for methods that can be used on arrays:

Table for methods that can be used on arrays

we can also use the following variables of Array class as shown in Table

table showing variables of array class

Python program to understand various methods of arrays class.

CopiedCopy Code

from array import* 
arr = array('i', [10,20,30,40,50,20]) 
print('Original array:', arr) 
arr.append(30) 
arr.append(60) 
print('After appending 30 and 60:', arr) 
arr.insert(1, 99) 
print('After inserting 99 in 1st position:', arr) 
arr.remove(20) 
print('After removing 20:', arr) 
n = arr.pop() 
print('Array after using pop():', arr) 
print('Popped element:', n) 
n = arr.index(30) 
print('First occurrence of element 30 is at:', n)
lst = arr.tolist() 
print('List:', lst) 
print('Array:', arr)