An array is a data structure that stores values of same data type. In Python, this is the main difference between arrays and lists.
While python lists can contain values corresponding to different data types, arrays in python can only contain values corresponding to same data type. In this tutorial, we will understand the Python arrays with few examples.
If you are new to Python, get started with the Python Introduction article.
To use arrays in python language, you need to import the standard
array module. This is because array is not a fundamental data type like strings, integer etc. Here is how you can import
array module in python :
from array import *
Once you have imported the
array module, you can declare an array. Here is how you do it:
arrayIdentifierName = array(typecode, [Initializers])
In the declaration above,
arrayIdentifierName is the name of array,
typecode lets python know the type of array and
Initializers are the values with which array is initialized.
Typecodes are the codes that are used to define the type of array values or the type of array. The table in the parameters section shows the possible values you can use when declaring an array and it's type.
Here is a real world example of python array declaration :
my_array = array('i',[1,2,3,4])
In the example above, typecode used is
i. This typecode represents signed integer whose size is 2 bytes.
Here is a simple example of an array containing 5 integers
from array import * my_array = array('i', [1,2,3,4,5]) for i in my_array: print(i) # 1 # 2 # 3 # 4 # 5