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