A Python Array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array).
For simplicity, we can think of an array a fleet of stairs where on each step is placed a value (let’s say one of your friends). Here, you can identify the location of any of your friends by simply knowing the count of the step they are on. Array can be handled in Python by a module named array. They can be useful when we have to manipulate only a specific data type values. A user can treat lists as arrays. However, user cannot constraint the type of elements stored in a list. If you create arrays using the array module, all elements of the array must be of the same type.
An array can be declared in various ways and different languages. The important points that should be considered are as follows:
- Index starts with 0.
- We can access each element via its index.
- The length of the array defines the capacity to store the elements.
Some of the basic operations supported by an array are as follows:
- Traverse – It prints all the elements one by one.
- Insertion – It adds an element at the given index.
- Deletion – It deletes an element at the given index.
- Search – It searches an element using the given index or by the value.
- Update – It updates an element at the given index.
The Array can be created in Python by importing the array module to the python program.
from array import * arrayName = array(typecode, [initializers])
Accessing array elements
We can access the array elements using the respective indices of those elements.
import array as arr a = arr.array('i', [2, 4, 6, 8]) print("First element:", a) print("Second element:", a) print("Second last element:", a[-1])
First element: 2 Second element: 4 Second last element: 8
We can easily concatenate any two arrays using the + symbol.
a=arr.array('d',[1.1 , 2.1 ,3.1,2.6,7.8]) b=arr.array('d',[3.7,8.6]) c=arr.array('d') c=a+b print("Array c = ",c)
Array c= array('d', [1.1, 2.1, 3.1, 2.6, 7.8, 3.7, 8.6])