blob: 4747b637581e72da1edf62010456e811f9e332b2 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`array` --- Efficient arrays of numeric values
3===================================================
4
5.. module:: array
6 :synopsis: Efficient arrays of uniformly typed numeric values.
7
8
9.. index:: single: arrays
10
11This module defines an object type which can efficiently represent an array of
12basic values: characters, integers, floating point numbers. Arrays are sequence
13types and behave very much like lists, except that the type of objects stored in
14them is constrained. The type is specified at object creation time by using a
15:dfn:`type code`, which is a single character. The following type codes are
16defined:
17
18+-----------+----------------+-------------------+-----------------------+
19| Type code | C Type | Python Type | Minimum size in bytes |
20+===========+================+===================+=======================+
21| ``'c'`` | char | character | 1 |
22+-----------+----------------+-------------------+-----------------------+
23| ``'b'`` | signed char | int | 1 |
24+-----------+----------------+-------------------+-----------------------+
25| ``'B'`` | unsigned char | int | 1 |
26+-----------+----------------+-------------------+-----------------------+
27| ``'u'`` | Py_UNICODE | Unicode character | 2 |
28+-----------+----------------+-------------------+-----------------------+
29| ``'h'`` | signed short | int | 2 |
30+-----------+----------------+-------------------+-----------------------+
31| ``'H'`` | unsigned short | int | 2 |
32+-----------+----------------+-------------------+-----------------------+
33| ``'i'`` | signed int | int | 2 |
34+-----------+----------------+-------------------+-----------------------+
35| ``'I'`` | unsigned int | long | 2 |
36+-----------+----------------+-------------------+-----------------------+
37| ``'l'`` | signed long | int | 4 |
38+-----------+----------------+-------------------+-----------------------+
39| ``'L'`` | unsigned long | long | 4 |
40+-----------+----------------+-------------------+-----------------------+
41| ``'f'`` | float | float | 4 |
42+-----------+----------------+-------------------+-----------------------+
43| ``'d'`` | double | float | 8 |
44+-----------+----------------+-------------------+-----------------------+
45
46The actual representation of values is determined by the machine architecture
47(strictly speaking, by the C implementation). The actual size can be accessed
48through the :attr:`itemsize` attribute. The values stored for ``'L'`` and
49``'I'`` items will be represented as Python long integers when retrieved,
50because Python's plain integer type cannot represent the full range of C's
51unsigned (long) integers.
52
53The module defines the following type:
54
55
56.. function:: array(typecode[, initializer])
57
58 Return a new array whose items are restricted by *typecode*, and initialized
Guido van Rossum98297ee2007-11-06 21:34:58 +000059 from the optional *initializer* value, which must be a list, object
60 supporting the buffer interface, or iterable over elements of the
61 appropriate type.
Georg Brandl116aa622007-08-15 14:28:22 +000062
Georg Brandl116aa622007-08-15 14:28:22 +000063 If given a list or string, the initializer is passed to the new array's
64 :meth:`fromlist`, :meth:`fromstring`, or :meth:`fromunicode` method (see below)
65 to add initial items to the array. Otherwise, the iterable initializer is
66 passed to the :meth:`extend` method.
67
68
69.. data:: ArrayType
70
71 Obsolete alias for :func:`array`.
72
Guido van Rossum98297ee2007-11-06 21:34:58 +000073.. data:: typecodes
74
75 A string with all available type codes.
76
Georg Brandl116aa622007-08-15 14:28:22 +000077Array objects support the ordinary sequence operations of indexing, slicing,
78concatenation, and multiplication. When using slice assignment, the assigned
79value must be an array object with the same type code; in all other cases,
80:exc:`TypeError` is raised. Array objects also implement the buffer interface,
81and may be used wherever buffer objects are supported.
82
83The following data items and methods are also supported:
84
85
86.. attribute:: array.typecode
87
88 The typecode character used to create the array.
89
90
91.. attribute:: array.itemsize
92
93 The length in bytes of one array item in the internal representation.
94
95
96.. method:: array.append(x)
97
98 Append a new item with value *x* to the end of the array.
99
100
101.. method:: array.buffer_info()
102
103 Return a tuple ``(address, length)`` giving the current memory address and the
104 length in elements of the buffer used to hold array's contents. The size of the
105 memory buffer in bytes can be computed as ``array.buffer_info()[1] *
106 array.itemsize``. This is occasionally useful when working with low-level (and
107 inherently unsafe) I/O interfaces that require memory addresses, such as certain
108 :cfunc:`ioctl` operations. The returned numbers are valid as long as the array
109 exists and no length-changing operations are applied to it.
110
111 .. note::
112
113 When using array objects from code written in C or C++ (the only way to
114 effectively make use of this information), it makes more sense to use the buffer
115 interface supported by array objects. This method is maintained for backward
116 compatibility and should be avoided in new code. The buffer interface is
117 documented in :ref:`bufferobjects`.
118
119
120.. method:: array.byteswap()
121
122 "Byteswap" all items of the array. This is only supported for values which are
123 1, 2, 4, or 8 bytes in size; for other types of values, :exc:`RuntimeError` is
124 raised. It is useful when reading data from a file written on a machine with a
125 different byte order.
126
127
128.. method:: array.count(x)
129
130 Return the number of occurrences of *x* in the array.
131
132
133.. method:: array.extend(iterable)
134
135 Append items from *iterable* to the end of the array. If *iterable* is another
136 array, it must have *exactly* the same type code; if not, :exc:`TypeError` will
137 be raised. If *iterable* is not an array, it must be iterable and its elements
138 must be the right type to be appended to the array.
139
Georg Brandl116aa622007-08-15 14:28:22 +0000140
141.. method:: array.fromfile(f, n)
142
143 Read *n* items (as machine values) from the file object *f* and append them to
144 the end of the array. If less than *n* items are available, :exc:`EOFError` is
145 raised, but the items that were available are still inserted into the array.
146 *f* must be a real built-in file object; something else with a :meth:`read`
147 method won't do.
148
149
150.. method:: array.fromlist(list)
151
152 Append items from the list. This is equivalent to ``for x in list:
153 a.append(x)`` except that if there is a type error, the array is unchanged.
154
155
156.. method:: array.fromstring(s)
157
158 Appends items from the string, interpreting the string as an array of machine
159 values (as if it had been read from a file using the :meth:`fromfile` method).
160
161
162.. method:: array.fromunicode(s)
163
164 Extends this array with data from the given unicode string. The array must
165 be a type ``'u'`` array; otherwise a :exc:`ValueError` is raised. Use
166 ``array.fromstring(unicodestring.encode(enc))`` to append Unicode data to an
167 array of some other type.
168
169
170.. method:: array.index(x)
171
172 Return the smallest *i* such that *i* is the index of the first occurrence of
173 *x* in the array.
174
175
176.. method:: array.insert(i, x)
177
178 Insert a new item with value *x* in the array before position *i*. Negative
179 values are treated as being relative to the end of the array.
180
181
182.. method:: array.pop([i])
183
184 Removes the item with the index *i* from the array and returns it. The optional
185 argument defaults to ``-1``, so that by default the last item is removed and
186 returned.
187
188
189.. method:: array.read(f, n)
190
191 .. deprecated:: 1.5.1
192 Use the :meth:`fromfile` method.
193
194 Read *n* items (as machine values) from the file object *f* and append them to
195 the end of the array. If less than *n* items are available, :exc:`EOFError` is
196 raised, but the items that were available are still inserted into the array.
197 *f* must be a real built-in file object; something else with a :meth:`read`
198 method won't do.
199
200
201.. method:: array.remove(x)
202
203 Remove the first occurrence of *x* from the array.
204
205
206.. method:: array.reverse()
207
208 Reverse the order of the items in the array.
209
210
211.. method:: array.tofile(f)
212
213 Write all items (as machine values) to the file object *f*.
214
215
216.. method:: array.tolist()
217
218 Convert the array to an ordinary list with the same items.
219
220
221.. method:: array.tostring()
222
223 Convert the array to an array of machine values and return the string
224 representation (the same sequence of bytes that would be written to a file by
225 the :meth:`tofile` method.)
226
227
228.. method:: array.tounicode()
229
230 Convert the array to a unicode string. The array must be a type ``'u'`` array;
231 otherwise a :exc:`ValueError` is raised. Use ``array.tostring().decode(enc)`` to
232 obtain a unicode string from an array of some other type.
233
234
235.. method:: array.write(f)
236
237 .. deprecated:: 1.5.1
238 Use the :meth:`tofile` method.
239
240 Write all items (as machine values) to the file object *f*.
241
242When an array object is printed or converted to a string, it is represented as
243``array(typecode, initializer)``. The *initializer* is omitted if the array is
244empty, otherwise it is a string if the *typecode* is ``'c'``, otherwise it is a
245list of numbers. The string is guaranteed to be able to be converted back to an
246array with the same type and value using :func:`eval`, so long as the
247:func:`array` function has been imported using ``from array import array``.
248Examples::
249
250 array('l')
251 array('c', 'hello world')
252 array('u', u'hello \u2641')
253 array('l', [1, 2, 3, 4, 5])
254 array('d', [1.0, 2.0, 3.14])
255
256
257.. seealso::
258
259 Module :mod:`struct`
260 Packing and unpacking of heterogeneous binary data.
261
262 Module :mod:`xdrlib`
263 Packing and unpacking of External Data Representation (XDR) data as used in some
264 remote procedure call systems.
265
266 `The Numerical Python Manual <http://numpy.sourceforge.net/numdoc/HTML/numdoc.htm>`_
267 The Numeric Python extension (NumPy) defines another array type; see
268 http://numpy.sourceforge.net/ for further information about Numerical Python.
269 (A PDF version of the NumPy manual is available at
270 http://numpy.sourceforge.net/numdoc/numdoc.pdf).
271