Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 149 ยท Data Structures

Arrays with the array Module

Learn when Python's array module beats lists. Store typed numbers compactly with array.array, and use bytes, bytearray and memoryview.

In many languages, an array is the basic way to store a sequence of values. In Python, that job usually goes to the list, so people often ask: "Does Python even have arrays?" It does. The standard library's array module provides array.array, a list-like sequence that stores numbers of one fixed type, packed tightly in memory.

That restriction is the point. A list can hold anything, which makes it flexible but heavy: each item is a full Python object, and the list only stores pointers to them. An array stores the raw numbers themselves, side by side, like C or Java would. In this lesson you'll learn when that matters, how to use array.array, and how it relates to Python's other binary types: bytes, bytearray and memoryview.

Creating an array

array.array() takes a typecode, a single letter that says what kind of number every item is, and an optional iterable of initial values:

Python Your first array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Most of what you know about lists carries over: indexing, slicing, len(), for loops, in, append(), extend(), insert(), pop(), remove(), index(), count() and reverse() all work. What's missing are methods that only make sense for mixed data, such as sort(). Use sorted(arr) for a sorted list, or array("i", sorted(arr)) to stay an array.

Typecodes

The typecode decides the item type and size. These are the ones you'll use most:

Typecode C type Python type Typical bytes
"b" / "B" signed / unsigned char int 1
"h" / "H" signed / unsigned short int 2
"i" / "I" signed / unsigned int int 4
"l" / "L" signed / unsigned long int 4 or 8
"q" / "Q" signed / unsigned long long int 8
"f" float float 4
"d" double float 8
"w" Unicode character str 4

Capital letters are unsigned: they hold only zero and positive numbers but reach twice as high. The exact size of some types depends on the platform, so check arr.itemsize instead of guessing. (The older "u" typecode for characters is deprecated; "w" replaced it in Python 3.13.)

Because every item has a fixed type and size, an array checks each value you put in:

Python Arrays enforce their type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last two lines show a real trade-off: "f" uses half the memory of "d" but keeps only about 7 significant digits. For general-purpose numbers, "d" matches Python's own float.

Why use an array? Memory

The main reason to pick an array over a list is memory. Compare a million small integers stored both ways:

Python List vs array memory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A list stores one pointer per item, and each pointer leads to a separate integer object. On a typical 64-bit computer that's 8 bytes for the pointer plus about 28 for the object. The array stores each number in 4 bytes, with nothing else. (The editors on this page run a 32-bit build of Python, so the sizes printed here are smaller than on your computer, but the gap is still large. Python also caches the integers from -5 to 256, so lists of tiny numbers are a little cheaper than this estimate.)

So when should you reach for array?

  • Large sequences of plain numbers: sensor readings, audio samples, pixel values, IDs.
  • Binary data exchange: arrays convert to and from raw bytes in one call, which suits files and network formats.
  • Not for mixed data or small collections. For a few hundred items, or anything that isn't a plain number, a list is simpler and just as good.

Arrays are not faster for arithmetic, though. A Python loop over an array is about as fast as a loop over a list, because each item still becomes a Python object while you work with it. For fast math on whole arrays, use NumPy (see below).

Arrays and raw bytes

An array is a thin wrapper around a block of bytes, and it can hand you those bytes directly. tobytes() and frombytes() convert in both directions, and tofile()/fromfile() do the same with binary files:

Python Saving numbers as binary data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Eight bytes for four numbers: no separators, no text, no wasted space. The catch is that the file only makes sense if the reader knows the typecode and byte order. Computers differ in byte order (endianness); byteswap() flips it when you need to match a file format. For structured binary records with mixed fields, the struct module is usually the better tool, and for exchanging data between programs a text format like JSON or CSV is easier to debug.

bytes, bytearray and memoryview

Python has three more built-in types for binary data. You'll meet them whenever you read binary files, talk to networks or encode text:

Type Mutable? What it is
bytes no an immutable sequence of integers 0โ€“255
bytearray yes a mutable version of bytes
memoryview (follows the source) a window onto another object's memory, without copying
Python bytes and bytearray

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that "Cafรฉ" is 4 characters but 5 bytes: UTF-8 needs two bytes for รฉ. Strings are text; bytes are what gets stored and sent. The Reading and Writing Files lesson explains encodings in more detail.

memoryview: slicing without copying

Slicing a bytes object or an array creates a copy. For large buffers, that's slow and wasteful. A memoryview lets you look at, and even edit, part of a buffer in place:

Python memoryview

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Any object that supports Python's buffer protocol works with memoryview: bytes, bytearray, array.array, and NumPy arrays. Library code for files, images and networking uses views to avoid copying megabytes of data. In everyday scripts you'll rarely need one, but now you'll recognize it.

When you need NumPy

array.array saves memory, but it doesn't do math on whole arrays at once. The third-party NumPy library does: multidimensional arrays, vectorized arithmetic (prices * 1.2 without a loop), statistics and linear algebra, all running in fast compiled code.

Python
import numpy as np

prices = np.array([4.5, 12.0, 7.25])
print(prices * 1.2)        # [ 5.4  14.4   8.7]
print(prices.mean())       # 7.916666666666667

A quick guide to choosing:

  • list: the default for any sequence, especially mixed or small data.
  • array.array: large, one-dimensional sequences of plain numbers when memory matters and you don't want a dependency.
  • bytes / bytearray: raw binary data, encoded text, file and network payloads.
  • NumPy: numerical work, math on whole arrays, tables and matrices. You'll try it in NumPy Basics.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the typecode in array("H", [1, 2, 3]) control?

    Each typecode maps to a C type. "H" is an unsigned short, typically 2 bytes holding 0 to 65,535.
  2. 2. What happens when you run array("B").append(300)?

    "B" stores unsigned bytes (0 to 255), and arrays check every value instead of silently wrapping.
  3. 3. Why does a large list of numbers use much more memory than an equivalent array?

    An array stores the raw numbers next to each other; a list stores references to full Python objects.
  4. 4. Which type lets you modify part of a large bytearray without copying it?

    A memoryview is a window onto another object's memory. Slicing it doesn't copy, and writes go straight to the original buffer.

Summary

  • array.array(typecode, values) stores numbers of one type packed tightly, with a list-like interface.
  • Typecodes such as "b", "i", "q" (signed), "B", "I", "Q" (unsigned), "f" and "d" (floats) fix the item type and size; out-of-range or wrong-type values raise errors.
  • Arrays use far less memory than lists of numbers, but they aren't faster for Python-level arithmetic.
  • tobytes(), frombytes(), tofile() and fromfile() move raw binary data in and out; byteswap() changes byte order.
  • bytes (immutable) and bytearray (mutable) hold raw binary data; memoryview slices buffers without copying.
  • For math on whole arrays, use NumPy.

Next: Functions, where you'll package code into reusable, named building blocks.