In Python, arrays are used to store multiple values in a single variable. While Python lists are more flexible and commonly used, Python also has a dedicated array
module for cases where all items are of the same data type — offering better memory efficiency and performance.
In this article, we’ll cover:
-
What arrays are and why use them
-
The difference between lists and arrays
-
Using the
array
module -
Common array operations
-
Iterating, slicing, and modifying arrays
-
Tips and common pitfalls
-
A complete example
What is an Array?
An array is a data structure that stores a collection of items of the same data type. Arrays can be more efficient than lists when dealing with large amounts of numerical data.
Python Lists vs Arrays
Feature | List | Array (array module) |
---|---|---|
Stores | Any data type | Same data type only |
Flexibility | Very flexible | Less flexible but efficient |
Performance | Slower for numeric operations | Faster for numeric operations |
Memory usage | Higher | Lower |
Importing the Array Module
To use arrays in Python, you need to import the built-in array
module:
import array
Creating an Array
Syntax:
array.array(typecode, initializer)
-
typecode
– represents the data type (e.g.,'i'
for integer) -
initializer
– optional list of values
Example:
import array
numbers = array.array('i', [1, 2, 3, 4])
print(numbers)
Output:
array('i', [1, 2, 3, 4])
Typecodes Table
Typecode | C Type | Python Type | Size (bytes) |
---|---|---|---|
'b' |
signed char | int | 1 |
'B' |
unsigned char | int | 1 |
'i' |
signed int | int | 2 or 4 |
'f' |
float | float | 4 |
'd' |
double | float | 8 |
'u' |
Unicode char | str (1 char) | 2 |
Basic Array Operations
✅ Accessing Elements
print(numbers[0]) # 1
✅ Modifying Elements
numbers[1] = 10
print(numbers) # array('i', [1, 10, 3, 4])
✅ Appending Elements
numbers.append(5)
✅ Inserting at a Position
numbers.insert(2, 99)
✅ Removing Elements
numbers.remove(3) # Removes the first occurrence of 3
✅ Popping Last Element
numbers.pop()
Iterating Through an Array
for num in numbers:
print(num)
Array Length
print(len(numbers)) # Number of elements
✂️ Slicing Arrays
print(numbers[1:4]) # Slices elements at index 1, 2, 3
Array Methods Overview
Method | Description |
---|---|
.append(x) |
Add an item to the end |
.insert(i, x) |
Insert at index i |
.remove(x) |
Remove first occurrence of x |
.pop([i]) |
Remove and return item at index i |
.index(x) |
Return index of first occurrence of x |
.reverse() |
Reverse array in place |
.buffer_info() |
Returns tuple (address, length) |
.count(x) |
Count occurrences of x |
.extend(iterable) |
Append elements from iterable |
Complete Example: Working with Float Array
import array
# Create array of floats
temperatures = array.array('f', [98.6, 99.4, 100.2, 97.8])
# Add a temperature
temperatures.append(98.0)
# Remove one
temperatures.remove(100.2)
# Calculate average
average = sum(temperatures) / len(temperatures)
print("Temperatures:", temperatures)
print("Average:", average)
Output:
Temperatures: array('f', [98.6, 99.4, 97.8, 98.0])
Average: 98.45
⚠️ Common Pitfalls
Pitfall | What Happens | Fix |
---|---|---|
Mixing data types | Raises TypeError |
Use same type throughout |
Using wrong typecode | Raises TypeError or OverflowError |
Refer to the typecode table |
Treating arrays like lists blindly | Some list methods don’t exist on arrays | Use .tolist() if needed |
Importing from numpy by mistake |
Confusing built-in array with NumPy | Use import array not import numpy |
Tips and Best Practices
-
✅ Use
array.array
when storing large numeric datasets and memory efficiency matters. -
✅ Use Python lists if you need to store mixed data types.
-
✅ Convert array to list if needed using
.tolist()
:
num_list = numbers.tolist()
-
✅ For scientific computing, use NumPy arrays, which are far more powerful than Python’s basic arrays.
What’s Next?
After understanding arrays, you might want to explore:
-
Lists vs Arrays in-depth
-
NumPy arrays for advanced numerical work
-
Memory profiling to compare performance
-
Using arrays in binary file I/O and data streams