Thursday, February 6, 2020

Python Arrays

Python Arrays


Array


Arrays are very much like lists in Python, However, the basic difference between the arrays and the lists in  Python is that the lists may have different types of elements stored in it, but an array can hold all the elements of the similar data type.

Formally, an array is the indexed collection of homogeneous elements(same type). Python does not have built-in support for arrays like other programming languages. So we need to import the array module to use arrays with the import statements.

import array as myarray


Creating an array


To create an array in Python, we can use array(arg1, arg2), constructor. The arg1 is the parameter that defines the type of element(as listed below in the table), and arg2 is the list containing the members of the array.

Table representing the parameter and their details
Parameter
Detail
b Represents signed integer of size 1 byte
B Represents unsigned integer of size 1 byte
c Represents character of size 1 byte
u Represents Unicode character of size 2 bytes
h Represents signed integer of size 2 bytes
H Represents unsigned integer of size 2 bytes
i Represents signed integer of size 2 bytes
I Represents unsigned integer of size 2 bytes
w Represents Unicode character of size 4 bytes
l Represents signed integer of size 4 bytes
L Represents unsigned integer of size 4 bytes
f Represents floating-point of size 4 bytes
d Represents floating-point of size 8 bytes

So, we can create an array as,

import array as arr #import array module
a=arr.array('i',[25,61,2,9,10,51]

Methods


Python arrays support several methods like

  • append()
  • pop()
  • remove()
  • reverse()
  • insert()
  • extend()
  • index()

Try Yourself: