How To Declare An Array In Python

Arrays are commonly used in programming to store and manage collections of items, such as numbers, strings, or other variables, in an organized and efficient way. In Python, arrays can be created using the built-in array module. In this tutorial, you will learn how to declare arrays and perform various operations on them in Python.

Step 1: Importing the array module

First, you need to import the array module using the import statement. Once you have imported the array module, it is available for you to use in your program:

Step 2: Creating an array

To create an array, you have to declare it using the array.array() function. This function takes two main arguments: the data type of the elements in the array, represented by a type code, and an iterable (e.g., list, tuple) containing the initial elements of the array.

The supported type codes are listed in the table below:

Type codePython typeMinimum size (bytes)
‘b’signed integer1
‘B’unsigned integer1
‘u’Unicode character2
‘h’signed integer2
‘H’unsigned integer2
‘i’signed integer2
‘I’unsigned integer2
‘l’signed integer4
‘L’unsigned integer4
‘f’floating-point4
‘d’floating-point8

For example, to create an array of integers, you can use the following code:

Step 3: Accessing elements

Array elements can be accessed by their index positions using square brackets []. Remember that in Python, indexing starts from 0. For example, to access the first element in the array, you can use the following code:

The output for the code will be:

The first element in the array is: 1

Step 4: Modifying elements

You can also modify the values of individual elements in an array. To update the value of an element, you can assign the new value to the element’s index position:

The output for the code will be:

The first element in the array is: 1
The updated array is: array('i', [1, 2, 10, 4, 5])