How to Create an Array in Python

Arrays are collections of similar kinds of data elements. The difference between a list and an array is a list can have a collection of items of different types.

Array methods are defined in the Array pacakge.

You need to import an array if you want to work with an array.

Here’s how to create an array

import array as arr
a = arr.array( 'd' , [1,2,3,4,5,6,7])
print(a)

Result

array( 'd' , [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0])
** Process exited - Return Code: 0 **
Press Enter to exit terminal

The above logic creates an array of decimal values. To avoid long names, you can use the as during import.

So far, well done.

Now, we see the syntax for an array. The array syntax has two arguments. Those are: data-type and the other is elements.

How to read array elements

Here’s the logic to read an array of elements.

import array as arr
a = arr.array('i', [9,3,2,90,65,23,45])
print("Element at index 0 is : ", a[0])
print("Element at index -3 is : ", a[-3])
print("Last element at index -1 is :", a[-1])

Result

Element at index 0 is : 9
Element at index -3 is : 65
Last element at index -1 is : 45
** Process exited - Return Code: 0 **
Press Enter to exit terminal

Data types to use while creating an array

Type codeValueMin size in bytes
‘b’Signed integer1
‘B’Unsigned integer1
‘i’Signed integer2
‘c’Character1
‘l’Unsigned integer2
‘f’Floating point4
‘d’Floating point8
‘u’Unicode character2
Data types you can use in an array

Properties of an array

  • Import the array module to work with it.
  • An array can have elements of the same data type.
  • Arrays are mutable and can change size dynamically (grow or shrink).  

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.