array
In Python, an array is a data structure that holds a sequence of objects of the same data type. Arrays allow you to reference multiple values with a single variable, and they can be indexed and iterated over.
Arrays are particularly useful when you need to store a large number of elements of the same type, such as integers or floats, and require operations to be performed on them efficiently.
The array
module provides an array()
function to create an array. You can specify the type of data the array will hold by providing a type code, such as "i"
for integers or "f"
for floats. This ensures that all elements in the array are of the specified type, which can lead to performance improvements when performing numerical operations.
Example
Here’s a quick example of how to use the array
module to create and manipulate an array of integers:
>>> import array
>>> numbers = array.array("i", [1, 2, 3, 4, 5])
>>> numbers[0]
1
>>> numbers[1] = 7
>>> numbers
array("i", [1, 7, 3, 4, 5])
>>> numbers.append(6)
>>> numbers
array("i", [1, 7, 3, 4, 5, 6])
>>> numbers.remove(3)
>>> numbers
array("i", [1, 7, 4, 5, 6])
Related Resources
Tutorial
Python's Array: Working With Numeric Data Efficiently
In this tutorial, you'll dive deep into working with numeric arrays in Python, an efficient tool for handling binary data. Along the way, you'll explore low-level data types exposed by the array module, emulate custom types, and even pass a Python array to C for high-performance processing.
For additional information on related topics, take a look at the following resources:
By Leodanis Pozo Ramos • Updated June 11, 2025