16.1. The array Module
The array module supplies a type, also called array, whose instances are mutable sequences, like lists. An array a is a one-dimensional sequence whose items can be only characters, or only numbers of one specific numeric type, fixed when you create a.
array.array's main advantage is that, compared to a list, it can save memory to hold objects all of the same (numeric or character) type. An array object a has a one-character, read-only attribute a.typecode, which is set on creation and gives the type of a's items. Table 16-1 shows the possible typecodes for array.
Table 16-1. Typecodes for the array module
str (length 1)
unicode (lenth 1)
The size in bytes of each item may be larger than the minimum, depending on the machine's architecture, and is available as the read-only attribute a.itemsize. Module array supplies just the type object called array.
Creates and returns an array object a with the given typecode. init can be a plain string whose length is a multiple of itemsize; the string's bytes, interpreted as machine values, directly initialize a's items. Alternatively, init can be any iterable (of characters when typecode is 'c', otherwise of numbers): each item of the iterable initializes one item of a.
Array objects expose all the methods and operations of mutable sequences (as covered in "Sequence Operations" on page 53), except method sort. Concatenation with + or +=, and assignment to slices, require both operands to be arrays with the same typecode; in contrast, the argument to a.extend can be any iterable with items acceptable to a. In addition to the methods of mutable sequences, an array object a exposes the following methods.
Swaps the byte order of each item of a.
Reads n items, taken as machine values, from file object f and appends the items to a. Note that f should be open for reading in binary modefor example, with mode 'rb'. When less than n items are available in f, fromfile raises EOFError after appending the items that are available.
Appends to a all items of list L.
Appends to a the bytes, interpreted as machine values, of string s. len(s) must be an exact multiple of a.itemsize.
Writes all items of a, taken as machine values, to file object f. Note that f should be open for writing in binary modefor example, with mode 'wb'.
Creates and returns a list object with the same items as a, like list(a).
Returns the string with the bytes from all items of a, taken as machine values. For any a, len(a.tostring( ))== len(a)*a.itemsize. f.write(a.tostring( )) is the same as a.tofile(f).