Table of Contents
ToggleUnlike languages like C++ or Java, Python lacks built-in arrays. Instead, it offers lists and tuples, which allow mixed types, or the array module for fixed-type arrays. In this lesson, we’ll explore arrays using the array module—perfect for efficient, same-type data storage.
An array is a container that holds a fixed number of items, all of the same type (e.g., integers, floats, strings). These elements are stored in contiguous memory locations, each with a numerical index starting at 0, used to identify and access them.
Arrays are visualized as a series of containers, indexed from 0 to n-1 (where n is the array size). For example, an array of length 10 can store 10 elements, with indices 0 to 9.
Key Points:
To create an array, import the array module and use the array() function with a typecode and optional initializer. Supported types include integers, floats, and Unicode characters.
import array as arr obj = arr.array(typecode, [initializer])
– typecode: Specifies element type (e.g., ‘i’ for integer).
– initializer: Optional list or iterable of values.
import array as arr
# Integer array
a = arr.array('i', [1, 2, 3])
print(type(a), a)
# Unicode char array
a = arr.array('u', 'BAT')
print(type(a), a)
# Float array
a = arr.array('d', [1.1, 2.2, 3.3])
print(type(a), a)
Output:
<class ‘array.array’> array(‘i’, [1, 2, 3])
<class ‘array.array’> array(‘u’, ‘BAT’)
<class ‘array.array’> array(‘d’, [1.1, 2.2, 3.3])
Array types are set by a single-character typecode. Here’s a table of common typecodes:
| Typecode | Python Data Type | Byte Size |
|---|---|---|
| ‘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 |
| ‘q’ | signed integer | 8 |
| ‘Q’ | unsigned integer | 8 |
| ‘f’ | floating point | 4 |
| ‘d’ | floating point | 8 |
Arrays support these operations: traverse, insertion, deletion, search, and update.
from array import *
array1 = array('i', [10, 20, 30, 40, 50])
print(array1[0])
print(array1[2])
Output: 10, 30
from array import *
array1 = array('i', [10, 20, 30, 40, 50])
array1.insert(1, 60)
for x in array1:
print(x)
Output: 10, 60, 20, 30, 40, 50
from array import *
array1 = array('i', [10, 20, 30, 40, 50])
array1.remove(40)
for x in array1:
print(x)
Output: 10, 20, 30, 50
from array import *
array1 = array('i', [10, 20, 30, 40, 50])
print(array1.index(40))
Output: 3
from array import *
array1 = array('i', [10, 20, 30, 40, 50])
array1[2] = 80
for x in array1:
print(x)
Output: 10, 20, 80, 40, 50
Key Takeaway: The array module offers a way to work with fixed-type arrays in Python—create them with typecodes and perform operations like insertion and deletion efficiently!
