8.6.array
— Efficient arrays of numeric values¶
This module defines an object type which can compactly represent an array ofbasic values: characters, integers, floating point numbers. Arrays are sequencetypes and behave very much like lists, except that the type of objects stored inthem is constrained. The type is specified at object creation time by using atype code, which is a single character. The following type codes aredefined:
Type code | C Type | Python Type | Minimum size in bytes |
---|---|---|---|
| char | character | 1 |
| signed char | int | 1 |
| unsigned char | int | 1 |
| Py_UNICODE | Unicode character | 2 (see note) |
| signed short | int | 2 |
| unsigned short | int | 2 |
| signed int | int | 2 |
| unsigned int | long | 2 |
| signed long | int | 4 |
| unsigned long | long | 4 |
| float | float | 4 |
| double | float | 8 |
Note
The'u'
typecode corresponds to Python’s unicode character. On narrowUnicode builds this is 2-bytes, on wide builds this is 4-bytes.
The actual representation of values is determined by the machine architecture(strictly speaking, by the C implementation). The actual size can be accessedthrough theitemsize
attribute. The values stored for'L'
and'I'
items will be represented as Python long integers when retrieved,because Python’s plain integer type cannot represent the full range of C’sunsigned (long) integers.
The module defines the following type:
- class
array.
array
(typecode[,initializer])¶ A new array whose items are restricted bytypecode, and initializedfrom the optionalinitializer value, which must be a list, string, or iterableover elements of the appropriate type.
Changed in version 2.4:Formerly, only lists or strings were accepted.
If given a list or string, the initializer is passed to the new array’s
fromlist()
,fromstring()
, orfromunicode()
method (see below)to add initial items to the array. Otherwise, the iterable initializer ispassed to theextend()
method.
Array objects support the ordinary sequence operations of indexing, slicing,concatenation, and multiplication. When using slice assignment, the assignedvalue must be an array object with the same type code; in all other cases,TypeError
is raised. Array objects also implement the buffer interface,and may be used wherever buffer objects are supported.
The following data items and methods are also supported:
array.
typecode
¶The typecode character used to create the array.
array.
itemsize
¶The length in bytes of one array item in the internal representation.
array.
append
(x)¶Append a new item with valuex to the end of the array.
array.
buffer_info
()¶Return a tuple
(address,length)
giving the current memory address and thelength in elements of the buffer used to hold array’s contents. The size of thememory buffer in bytes can be computed asarray.buffer_info()[1]*array.itemsize
. This is occasionally useful when working with low-level (andinherently unsafe) I/O interfaces that require memory addresses, such as certainioctl()
operations. The returned numbers are valid as long as the arrayexists and no length-changing operations are applied to it.Note
When using array objects from code written in C or C++ (the only way toeffectively make use of this information), it makes more sense to use the bufferinterface supported by array objects. This method is maintained for backwardcompatibility and should be avoided in new code. The buffer interface isdocumented inBuffers and Memoryview Objects.
array.
byteswap
()¶“Byteswap” all items of the array. This is only supported for values which are1, 2, 4, or 8 bytes in size; for other types of values,
RuntimeError
israised. It is useful when reading data from a file written on a machine with adifferent byte order.
array.
count
(x)¶Return the number of occurrences ofx in the array.
array.
extend
(iterable)¶Append items fromiterable to the end of the array. Ifiterable is anotherarray, it must haveexactly the same type code; if not,
TypeError
willbe raised. Ifiterable is not an array, it must be iterable and its elementsmust be the right type to be appended to the array.Changed in version 2.4:Formerly, the argument could only be another array.
array.
fromfile
(f,n)¶Readn items (as machine values) from the file objectf and append them tothe end of the array. If less thann items are available,
EOFError
israised, but the items that were available are still inserted into the array.f must be a real built-in file object; something else with aread()
method won’t do.
array.
fromlist
(list)¶Append items from the list. This is equivalent to
forxinlist:a.append(x)
except that if there is a type error, the array is unchanged.
array.
fromstring
(s)¶Appends items from the string, interpreting the string as an array of machinevalues (as if it had been read from a file using the
fromfile()
method).
array.
fromunicode
(s)¶Extends this array with data from the given unicode string. The array mustbe a type
'u'
array; otherwise aValueError
is raised. Usearray.fromstring(unicodestring.encode(enc))
to append Unicode data to anarray of some other type.
array.
index
(x)¶Return the smallesti such thati is the index of the first occurrence ofx in the array.
array.
insert
(i,x)¶Insert a new item with valuex in the array before positioni. Negativevalues are treated as being relative to the end of the array.
array.
pop
([i])¶Removes the item with the indexi from the array and returns it. The optionalargument defaults to
-1
, so that by default the last item is removed andreturned.
array.
read
(f,n)¶Deprecated since version 1.5.1:Use the
fromfile()
method.Readn items (as machine values) from the file objectf and append them tothe end of the array. If less thann items are available,
EOFError
israised, but the items that were available are still inserted into the array.f must be a real built-in file object; something else with aread()
method won’t do.
array.
remove
(x)¶Remove the first occurrence ofx from the array.
array.
reverse
()¶Reverse the order of the items in the array.
array.
tofile
(f)¶Write all items (as machine values) to the file objectf.
array.
tolist
()¶Convert the array to an ordinary list with the same items.
array.
tostring
()¶Convert the array to an array of machine values and return the stringrepresentation (the same sequence of bytes that would be written to a file bythe
tofile()
method.)
array.
tounicode
()¶Convert the array to a unicode string. The array must be a type
'u'
array;otherwise aValueError
is raised. Usearray.tostring().decode(enc)
toobtain a unicode string from an array of some other type.
array.
write
(f)¶Deprecated since version 1.5.1:Use the
tofile()
method.Write all items (as machine values) to the file objectf.
When an array object is printed or converted to a string, it is represented asarray(typecode,initializer)
. Theinitializer is omitted if the array isempty, otherwise it is a string if thetypecode is'c'
, otherwise it is alist of numbers. The string is guaranteed to be able to be converted back to anarray with the same type and value usingeval()
, so long as thearray
class has been imported usingfromarrayimportarray
.Examples:
array('l')array('c','hello world')array('u',u'hello\u2641')array('l',[1,2,3,4,5])array('d',[1.0,2.0,3.14])
See also
- Module
struct
Packing and unpacking of heterogeneous binary data.
- Module
xdrlib
Packing and unpacking of External Data Representation (XDR) data as used in someremote procedure call systems.
- The Numerical Python Documentation
The Numeric Python extension (NumPy) defines another array type; seehttp://www.numpy.org/ for further information about Numerical Python.