What are Arrays?
An array is a data structure for storing more than one data item that has a similar data type. The items of an array are allocated at adjacent memory locations. These memory locations are called elements of that array.
The total number of elements in an array is called length. The details of an array are accessed about its position. This reference is called index or subscript.
Concept Diagram of Arrays
The above diagram illustrates that:
Note:
The following diagram illustrates the syntax of declaring an array in Python and C++ to present that the comprehension remains the same though the syntax may slightly vary in different languages.
Understand Syntax of Arrays
Here, are some reasons for using arrays:
In Python, arrays are different from lists; lists can have array items of data types, whereas arrays can only have items of the same data type.
Python has a separate module for handling arrays called array, which you need to import before you start working on them.
Note: The array must contain real numbers like integers and floats, no strings allowed.
The following code illustrates how you can create an integer array in python to store account balance:
import array
balance = array.array('i', [300,200,100])
print(balance)
You can declare an array in Python while initializing it using the following syntax.
arrayName = array.array(type code for data type, [array,items])
The following image explains the syntax.
Syntax of Array in Python
The following table illustrates the typecodes available for supported data types:
Type code |
C Type |
Python Type |
Minimum size in bytes |
'c' |
char |
character |
1 |
'B' |
unsigned char |
int |
1 |
'b' |
signed char |
int |
1 |
'u' |
Py_UNICODE |
Unicode character |
2 |
'h' |
signed short |
int |
2 |
'H' |
unsigned short |
int |
2 |
'i' |
signed int |
int |
2 |
'I' |
unsigned int |
long |
2 |
'l' |
signed long |
int |
4 |
'L' |
unsigned long |
long |
4 |
'f' |
float |
float |
4 |
'd' |
double |
float |
8 |
You can access any array item by using its index.
SYNTAX
arrayName[indexNum]
EXAMPLE
balance[1]
The following image illustrates the basic concept of accessing arrays items by their index.
Access an Array Element
Here, we have accessed the second value of the array using its index, which is 1. The output of this will be 200, which is basically the second value of the balanced array.
import array
balance = array.array('i', [300,200,100])
print(balance[1])
OUTPUT
200