The array Module
The array module implements an efficient array storage type. Arrays are
similar to lists, but all items must be of the same primitive type.
The type is defined when the array is created.
Examples 4-1 through 4-5 are simple ones. Example 4-1 creates an
array object and copies the internal buffer to
a string through the tostring method.
Example 4-1. Using the array Module to Convert Lists of Integers to Strings
File: array-example-1.py
import array
a = array.array("B", range(16)) # unsigned char
b = array.array("h", range(16)) # signed short
print a
print repr(a.tostring())
print b
print repr(b.tostring())
array('B', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
'\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017'
array('h', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
'\000\000\001\000\002\000\003\000\004\000\005\000\006\000\007\000
\010\000\011\000\012\000\013\000\014\000\015\000\016\000\017\000'The array objects can be treated as ordinary
lists to some extent, as Example 4-2 shows. You cannot concatenate arrays if they have
different type codes, though.
Example 4-2. Using Arrays as Ordinary Sequences
File: array-example-2.py
import array
a = array.array("B", [1, 2, 3])
a.append(4)
a = a + a
a = a[2:-2]
print a
print repr(a.tostring())
for i in a:
print i,
array('B', [3, 4, 1, 2])
'\003\004\001\002'
3 4 1 2This module also provides a very efficient way to turn raw binary data into a sequence of integers (or floating point values, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access