array

The Python array module provides an efficient data structure for creating arrays of values—often numbers—, which are stored more compactly than in standard lists.

Arrays can be particularly useful for handling large data sets where memory efficiency is a concern.

Here’s a quick example of an array containing integers:

Python
>>> import array
>>> array.array('i', [1, 2, 3, 4])
array('i', [1, 2, 3, 4])

Key Features

  • Creates arrays with elements of a specified data type
  • Offers more memory-efficient storage for homogeneous numeric data compared to lists
  • Supports all basic operations like slicing, indexing, and iteration

Frequently Used Classes and Functions

Object Type Description
array Class Creates array objects that store items of a specific type
array.typecode Attribute Returns a character code representing the type of items
array.append() Method Adds an element to the end of the array
array.extend() Method Appends items from an iterable
array.insert() Method Inserts an item in a specific position

Examples

Create an array of integers:

Python
>>> import array

>>> numbers = array.array('i', [1, 2, 3, 4])
>>> numbers
array('i', [1, 2, 3, 4])

Append an element to the array:

Python
>>> numbers.append(5)
>>> numbers
array('i', [1, 2, 3, 4, 5])

Extend the array with elements from an iterable:

Python
>>> numbers.extend([6, 7, 8])
>>> numbers
array('i', [1, 2, 3, 4, 5, 6, 7, 8])

Common Use Cases

  • Handling large sequences of numbers with less memory overhead
  • Performing numerical operations on values of homogeneous data types
  • Interfacing with C libraries that require contiguous data

Real-World Example

Suppose you need to process a large file of integers and calculate their sum efficiently. Here’s how you can do it using the array module. Note that for this code to work, you need an integers.bin file with appropriate content:

Python
>>> import array
>>> import os

>>> # Simulate the binary file
>>> numbers = array.array("i", [10, 20, 30, 40, 50])
>>> with open("integers.bin", "wb") as file:
...     file.write(numbers.tobytes())
...
20

>>> loaded_numbers = array.array("i")
>>> with open("integers.bin", "rb") as file:
...     loaded_numbers.frombytes(file.read())
...

>>> sum(loaded_numbers)
150

By using the array module, the code efficiently reads binary data and computes the sum with minimal memory usage, demonstrating the module’s utility in handling large data sets.

Tutorial

Python's list Data Type: A Deep Dive With Examples

In this tutorial, you'll dive deep into Python's lists. You'll learn how to create them, update their content, populate and grow them, and more. Along the way, you'll code practical examples that will help you strengthen your skills with this fundamental data type in Python.

intermediate data-structures python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated June 23, 2025