Python Arrays
Python has no built-in array type the way C does. Day to day you use a Python list. This page is for the remaining cases: the array module, and when to switch to NumPy.
Python Arrays
If you searched for “Python arrays” because you want a list of values you can loop over, start with the Python lists tutorial. Lists are the default sequence in Python: mixed types, easy appends, slicing.
Use this page when you need a typed, compact sequence (array.array) or a numeric grid (NumPy arrays). Do not treat this chapter as a second lists tutorial.
Arrays
Arrays are used to store multiple values in one single variable:
Example - Create an array containing car names:
cars = ["Ford", "Volvo", "BMW"]What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
car1 = "Ford"
car2 = "Volvo"
car3 = "BMW"However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can access the values by referring to an index number.
Access the Elements of an Array
You refer to an array element by referring to the index number.
Example - Get the value of the first array item:
cars = ["Ford", "Volvo", "BMW"]
x = cars[0]
print(x)Example - Modify the value of the first array item:
cars = ["Ford", "Volvo", "BMW"]
cars[0] = "Toyota"
print(cars)The Length of an Array
Use the len() method to return the length of an array (the number of elements in an array).
Example - Return the number of elements in the cars array:
cars = ["Ford", "Volvo", "BMW"]
x = len(cars)
print(x)Note: The length of an array is always one more than the highest array index.
Looping Array Elements
You can use the for in loop to loop through all the elements of an array.
Example - Print each item in the cars array:
cars = ["Ford", "Volvo", "BMW"]
for x in cars:
print(x)Adding Array Elements
You can use the append() method to add an element to an array.
Example - Add one more element to the cars array:
cars = ["Ford", "Volvo", "BMW"]
cars.append("Honda")
print(cars)Removing Array Elements
You can use the pop() method to remove an element from the array.
Example - Delete the second element of the cars array:
cars = ["Ford", "Volvo", "BMW"]
cars.pop(1)
print(cars)You can also use the remove() method to remove an element from the array.
Example - Delete the element that has the value "Volvo":
cars = ["Ford", "Volvo", "BMW"]
cars.remove("Volvo")
print(cars)Note: The list's remove() method only removes the first occurrence of the specified value.
Array Methods
Python has a set of built-in methods that you can use on lists/arrays.
The Array Module
Python has a built-in array module that provides a more efficient way to work with arrays of numeric data.
Example - Import and use the array module:
import array
# Create an array of integers
numbers = array.array('i', [1, 2, 3, 4, 5])
print(numbers)
# Create an array of floats
floats = array.array('f', [1.1, 2.2, 3.3, 4.4])
print(floats)Array Type Codes
Array Module Methods
Example - Working with array methods:
import array
# Create an array
arr = array.array('i', [1, 2, 3, 4, 5])
# Append an element
arr.append(6)
print(arr) # array('i', [1, 2, 3, 4, 5, 6])
# Insert an element at specific position
arr.insert(0, 0)
print(arr) # array('i', [0, 1, 2, 3, 4, 5, 6])
# Remove an element
arr.remove(3)
print(arr) # array('i', [0, 1, 2, 4, 5, 6])
# Pop an element
popped = arr.pop()
print(f"Popped: {popped}") # Popped: 6
print(arr) # array('i', [0, 1, 2, 4, 5])
# Get array info
print(f"Length: {len(arr)}")
print(f"Type code: {arr.typecode}")
print(f"Item size: {arr.itemsize} bytes")NumPy Arrays
For more advanced array operations, Python developers often use NumPy, which provides powerful array operations:
Example - NumPy array (requires installation: pip install numpy):
import numpy as np
# Create a NumPy array
arr = np.array([1, 2, 3, 4, 5])
print(arr)
# Array operations
print(arr * 2) # Multiply all elements by 2
print(arr + 10) # Add 10 to all elements
print(arr.sum()) # Sum of all elements
print(arr.mean()) # Mean of all elements
# 2D array
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix)
print(matrix.shape) # (2, 3)When to Use Each Type
Python Lists
- General-purpose, flexible
- Can store different data types
- Good for most applications
- Built-in to Python
Array Module
- More memory efficient
- Only stores one data type
- Good for large numeric datasets
- Built-in to Python
NumPy Arrays
- Fastest for numerical operations
- Advanced mathematical functions
- Multi-dimensional arrays
- Requires separate installation
List vs array vs NumPy
In Python, "array" can mean three different things. Choose based on your data.
| Type | Import | Use for |
|---|---|---|
list | built-in | General mixed-type sequences |
array.array | from array import array | Compact single-type numeric data |
numpy.ndarray | import numpy as np | Fast vectorized math, matrices |
import numpy as np
a = np.array([1, 2, 3, 4])
print(a * 2) # [2 4 6 8] -> elementwise, no loop
print(a.mean()) # 2.5
print(a[a > 2]) # [3 4] -> boolean filteringTry It Yourself
Exercise 1: Loop through a list of cars and print each one with its index.
Show solution
cars = ["Ford", "BMW", "Volvo"]
for i, car in enumerate(cars):
print(i, car)Exercise 2: Using NumPy, create an array of 1–5 and print the sum of its squares.
Show solution
import numpy as np
a = np.array([1, 2, 3, 4, 5])
print((a ** 2).sum()) # 55Key Takeaways
- Python has no native fixed array — the
listis the everyday sequence. - Use
array.arrayfor compact same-type numbers. - Use NumPy for fast, vectorized numeric work.
📘 Real-World Deep Dive
Python has no built-in "array" type in the C sense — a <code>list</code> does the job 95% of the time. The 5% where it doesn't (millions of numbers, fixed-width binary, tight memory) is exactly where knowing <code>array.array</code> and NumPy saves you from a slow, RAM-hungry program.
Real-Life Scenario
A weather station streams a temperature reading every minute. We keep the last N readings and report a moving average — the kind of rolling buffer you meet in monitoring, audio, and IoT code.
Real-Life Example
from collections import deque
class RollingAverage:
def __init__(self, window: int):
self.readings = deque(maxlen=window) # drops the oldest automatically
def add(self, value: float) -> float:
self.readings.append(value)
return sum(self.readings) / len(self.readings)
temps = RollingAverage(window=3)
for reading in [20.1, 20.4, 21.0, 22.5, 23.1]:
print(f"{reading:5.1f} -> avg {temps.add(reading):.2f}")A deque with maxlen is the idiomatic fixed-size buffer — no manual slicing to trim the front.
Expected Output
20.1 -> avg 20.10
20.4 -> avg 20.25
21.0 -> avg 20.50
22.5 -> avg 21.30
23.1 -> avg 22.20Common mistakes
- A plain
listgrows without bound. If you only ever need the last N items, usedeque(maxlen=N)so old items fall off on their own. - Trimming with
lst = lst[1:]in a loop looks harmless but rebuilds the whole list every time — O(n) per step, O(n²) overall. - Reaching for NumPy to store 20 numbers is overkill; reaching for a
listto store 20 million floats will eat gigabytes. Match the tool to the size.
🚀 Performance & Best Practices
array.array('d', ...)stores raw doubles — roughly 8 bytes each vs. ~28 for a Python float object in a list.- For any real math on numeric arrays (sums, dot products, filtering), a NumPy array is both shorter to write and 10–100× faster than a Python loop.
deque.append/popleftare O(1); doing the same at the front of alistis O(n).
🧪 Try It Yourself
- Extend
RollingAveragewith amax()method that reports the largest reading still in the window. - Swap the
dequefor a plain list and print both — convince yourself the memory keeps growing. - Rewrite the averaging with
numpyand time both versions over 1,000,000 readings.