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:
1 |
import array |
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 code | Python type | Minimum size (bytes) |
---|---|---|
‘b’ | signed integer | 1 |
‘B’ | unsigned integer | 1 |
‘u’ | Unicode character | 2 |
‘h’ | signed integer | 2 |
‘H’ | unsigned integer | 2 |
‘i’ | signed integer | 2 |
‘I’ | unsigned integer | 2 |
‘l’ | signed integer | 4 |
‘L’ | unsigned integer | 4 |
‘f’ | floating-point | 4 |
‘d’ | floating-point | 8 |
For example, to create an array of integers, you can use the following code:
1 2 |
import array my_array = array.array('i', [1, 2, 3, 4, 5]) |
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:
1 2 |
first_element = my_array[0] print("The first element in the array is:", first_element) |
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:
1 2 |
my_array[2] = 10 print("The updated array is:", my_array) |
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])