Arrays in Python — array Module and NumPy
Arrays in Python
Python doesn't have a built-in array type like C or Java. Instead, you have three options depending on your needs:
Using Lists as Arrays
For most use cases, Python lists work perfectly as arrays.
scores = [85, 92, 78, 95, 88]
# Access by index
print(scores[0]) # 85
print(scores[-1]) # 88
# Modify
scores[2] = 80
scores.append(91)
# Iterate
for score in scores:
print(score)
# 2D array (list of lists)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[1][2]) # 6
# Traverse 2D array
for row in matrix:
for val in row:
print(val, end=" ")
print()
The array Module
The built-in array module provides typed arrays - all elements must be the same type. More memory-efficient than lists for large numeric data.
import array
# array(typecode, initializer)
# 'i' = signed int, 'f' = float, 'd' = double
nums = array.array('i', [1, 2, 3, 4, 5])
floats = array.array('f', [1.1, 2.2, 3.3])
print(nums[0]) # 1
print(nums[1:3]) # array('i', [2, 3])
nums.append(6)
nums.insert(0, 0)
nums.remove(3)
print(nums) # array('i', [0, 1, 2, 4, 5, 6])
# Convert to list
as_list = nums.tolist()
print(as_list) # [0, 1, 2, 4, 5, 6]
| Type Code | C Type | Python Type | Size |
|---|---|---|---|
'b' | signed char | int | 1 byte |
'B' | unsigned char | int | 1 byte |
'i' | signed int | int | 2 bytes |
'I' | unsigned int | int | 2 bytes |
'l' | signed long | int | 4 bytes |
'f' | float | float | 4 bytes |
'd' | double | float | 8 bytes |
NumPy Arrays
NumPy is the go-to library for numerical computing. Its ndarray supports multi-dimensional arrays and vectorized math operations.
import numpy as np
# Create arrays
a = np.array([1, 2, 3, 4, 5])
b = np.zeros(5) # [0. 0. 0. 0. 0.]
c = np.ones((2, 3)) # 2x3 matrix of ones
d = np.arange(0, 10, 2) # [0 2 4 6 8]
e = np.linspace(0, 1, 5) # [0. 0.25 0.5 0.75 1. ]
# Shape and dimensions
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix.shape) # (2, 3)
print(matrix.ndim) # 2
print(matrix.dtype) # int64
# Vectorized operations (no loops needed!)
x = np.array([1, 2, 3, 4])
print(x * 2) # [2 4 6 8]
print(x ** 2) # [1 4 9 16]
print(x + x) # [2 4 6 8]
# Slicing
print(matrix[0, :]) # [1 2 3] - first row
print(matrix[:, 1]) # [2 5] - second column
print(matrix[1, 1:]) # [5 6]
# Aggregate functions
print(np.sum(x)) # 10
print(np.mean(x)) # 2.5
print(np.max(x)) # 4
print(np.std(x)) # standard deviation
Level Up Your Python Skills
Master Python with these hand-picked resources
10,000+ learners
Free forever
Updated 2026
Related Python Topics