Python Array Module
The array module defines an object type which can efficiently represent an array of basic values: characters, integers, floating point numbers. Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained.
Importing the Module
import array
Creating Arrays
To create an array, you need to specify a type code (a single character) that defines the type of the elements.
Common Type Codes
| Type Code | C Type | Python Type | Minimum Size in Bytes |
|---|---|---|---|
'b' |
signed char | int | 1 |
'B' |
unsigned char | int | 1 |
'h' |
signed short | int | 2 |
'H' |
unsigned short | int | 2 |
'i' |
signed int | int | 2 |
'I' |
unsigned int | int | 2 |
'l' |
signed long | int | 4 |
'L' |
unsigned long | int | 4 |
'f' |
float | float | 4 |
'd' |
double | float | 8 |
Example
import array
# Create an array of integers (signed int)
a = array.array('i', [1, 2, 3, 4, 5])
print(a)
# Output: array('i', [1, 2, 3, 4, 5])
Basic Operations
Arrays support standard sequence operations like indexing, slicing, concatenation, and multiplication.
print(a[0]) # Output: 1
print(a[1:3]) # Output: array('i', [2, 3])
Methods
append()
Append a new item to the end of the array.
a.append(6)
print(a)
extend()
Append items from an iterable to the end of the array.
a.extend([7, 8, 9])
print(a)
insert()
Insert a new item into the array at a given position.
a.insert(0, 0)
print(a)
remove()
Remove the first occurrence of a value from the array.
a.remove(0)
print(a)
tolist()
Convert the array to an ordinary list with the same items.
l = a.tolist()
print(l)