Python Array Module

There are three ways to import the array module into our program.

Array Module

The first way is to import the entire array module using import statement as,

CopiedCopy Code

import array

When we import the array module, we are able to get the 'array' class of that module that helps us to create an array. See the following example:

CopiedCopy Code

a =array.array('i',[4,6,2,9])
							

Here, the first 'array' represents the module name and the next 'array' represents the class name for which the object is created. We should understand that we are creating our array as an object of array class.

The second way of importing the array module is to give it an alias name, as:

CopiedCopy Code

import array as ar
							

Here, the array is imported with an alternate name 'ar'. Hence we can refer to the array class of 'ar' module as:

CopiedCopy Code

a =ar.array('i', [4,6,2,9]) 
							

The third way of importing the array module is to write:

CopiedCopy Code

from array import * 
							

Observe the '*' symbol that represents 'all'. The meaning of this statement is this: import all (classes, objects, variables etc) from the array module into our program. That means we are specifically importing the 'array' class (because of * symbol) of 'array' module. So, there is no need to mention the module name before our array name while creating it. We can create the array as:

CopiedCopy Code

a =array('i',[4,6,2,9])
							

Python program to create an integer type array.

CopiedCopy Code

import array 
a = array.array('i', [5, 6, -7, 8]) 
print('The array elements are:') 
for element in a: 
   print(element)

Python program to create an integer type array.

CopiedCopy Code

from array import * 
a = array('i', [5, 6, -7, 8]) 
print('The array elements are:') 
for element in a: 
    print(element)

A Python program to create an array with a group of characters.

CopiedCopy Code

from array import * 
arr = array('u', ['a','b','c','d','e']) 
print('The array elements are:') 
for ch in arr: 
   print(ch)