Debian Codegraph @

Doc/library/array.rst

raw
1 :mod:`!array` --- Efficient arrays of numeric values
2 ====================================================
3
4 .. module:: array
5 :synopsis: Space efficient arrays of uniformly typed numeric values.
6
7 .. index:: single: arrays
8
9 --------------
10
11 This module defines an object type which can compactly represent an array of
12 basic values: characters, integers, floating-point numbers. Arrays are mutable :term:`sequence`
13 types and behave very much like lists, except that the type of objects stored in
14 them 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
16 defined:
17
18 +-----------+--------------------+-------------------+-----------------------+-------+
19 | Type code | C Type | Python Type | Minimum size in bytes | Notes |
20 +===========+====================+===================+=======================+=======+
21 | ``'b'`` | signed char | int | 1 | |
22 +-----------+--------------------+-------------------+-----------------------+-------+
23 | ``'B'`` | unsigned char | int | 1 | |
24 +-----------+--------------------+-------------------+-----------------------+-------+
25 | ``'u'`` | wchar_t | Unicode character | 2 | \(1) |
26 +-----------+--------------------+-------------------+-----------------------+-------+
27 | ``'w'`` | Py_UCS4 | Unicode character | 4 | \(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 | int | 2 | |
36 +-----------+--------------------+-------------------+-----------------------+-------+
37 | ``'l'`` | signed long | int | 4 | |
38 +-----------+--------------------+-------------------+-----------------------+-------+
39 | ``'L'`` | unsigned long | int | 4 | |
40 +-----------+--------------------+-------------------+-----------------------+-------+
41 | ``'q'`` | signed long long | int | 8 | |
42 +-----------+--------------------+-------------------+-----------------------+-------+
43 | ``'Q'`` | unsigned long long | int | 8 | |
44 +-----------+--------------------+-------------------+-----------------------+-------+
45 | ``'f'`` | float | float | 4 | |
46 +-----------+--------------------+-------------------+-----------------------+-------+
47 | ``'d'`` | double | float | 8 | |
48 +-----------+--------------------+-------------------+-----------------------+-------+
49
50 Notes:
51
52 (1)
53 It can be 16 bits or 32 bits depending on the platform.
54
55 .. versionchanged:: 3.9
56 ``array('u')`` now uses :c:type:`wchar_t` as C type instead of deprecated
57 ``Py_UNICODE``. This change doesn't affect its behavior because
58 ``Py_UNICODE`` is alias of :c:type:`wchar_t` since Python 3.3.
59
60 .. deprecated-removed:: 3.3 3.16
61 Please migrate to ``'w'`` typecode.
62
63 (2)
64 .. versionadded:: 3.13
65
66 .. seealso::
67
68 The :ref:`ctypes <ctypes-fundamental-data-types>` and
69 :ref:`struct <format-characters>` modules,
70 as well as third-party modules like `numpy <https://numpy.org/doc/stable/reference/arrays.interface.html#object.__array_interface__>`__,
71 use similar -- but slightly different -- type codes.
72
73
74 The actual representation of values is determined by the machine architecture
75 (strictly speaking, by the C implementation). The actual size can be accessed
76 through the :attr:`array.itemsize` attribute.
77
78 The module defines the following item:
79
80
81 .. data:: typecodes
82
83 A string with all available type codes.
84
85
86 The module defines the following type:
87
88
89 .. class:: array(typecode[, initializer])
90
91 A new array whose items are restricted by *typecode*, and initialized
92 from the optional *initializer* value, which must be a :class:`bytes`
93 or :class:`bytearray` object, a Unicode string, or iterable over elements
94 of the appropriate type.
95
96 If given a :class:`bytes` or :class:`bytearray` object, the initializer
97 is passed to the new array's :meth:`frombytes` method;
98 if given a Unicode string, the initializer is passed to the
99 :meth:`fromunicode` method;
100 otherwise, the initializer's iterator is passed to the :meth:`extend` method
101 to add initial items to the array.
102
103 Array objects support the ordinary :ref:`mutable <typesseq-mutable>` :term:`sequence` operations of indexing, slicing,
104 concatenation, and multiplication. When using slice assignment, the assigned
105 value must be an array object with the same type code; in all other cases,
106 :exc:`TypeError` is raised. Array objects also implement the buffer interface,
107 and may be used wherever :term:`bytes-like objects <bytes-like object>` are supported.
108
109 .. audit-event:: array.__new__ typecode,initializer array.array
110
111
112 .. attribute:: typecode
113
114 The typecode character used to create the array.
115
116
117 .. attribute:: itemsize
118
119 The length in bytes of one array item in the internal representation.
120
121
122 .. method:: append(value, /)
123
124 Append a new item with the specified value to the end of the array.
125
126
127 .. method:: buffer_info()
128
129 Return a tuple ``(address, length)`` giving the current memory address and the
130 length in elements of the buffer used to hold array's contents. The size of the
131 memory buffer in bytes can be computed as ``array.buffer_info()[1] *
132 array.itemsize``. This is occasionally useful when working with low-level (and
133 inherently unsafe) I/O interfaces that require memory addresses, such as certain
134 :c:func:`!ioctl` operations. The returned numbers are valid as long as the array
135 exists and no length-changing operations are applied to it.
136
137 .. note::
138
139 When using array objects from code written in C or C++ (the only way to
140 effectively make use of this information), it makes more sense to use the buffer
141 interface supported by array objects. This method is maintained for backward
142 compatibility and should be avoided in new code. The buffer interface is
143 documented in :ref:`bufferobjects`.
144
145
146 .. method:: byteswap()
147
148 "Byteswap" all items of the array. This is only supported for values which are
149 1, 2, 4, or 8 bytes in size; for other types of values, :exc:`RuntimeError` is
150 raised. It is useful when reading data from a file written on a machine with a
151 different byte order.
152
153
154 .. method:: count(value, /)
155
156 Return the number of occurrences of *value* in the array.
157
158
159 .. method:: extend(iterable, /)
160
161 Append items from *iterable* to the end of the array. If *iterable* is another
162 array, it must have *exactly* the same type code; if not, :exc:`TypeError` will
163 be raised. If *iterable* is not an array, it must be iterable and its elements
164 must be the right type to be appended to the array.
165
166
167 .. method:: frombytes(buffer, /)
168
169 Appends items from the :term:`bytes-like object`, interpreting
170 its content as an array of machine values (as if it had been read
171 from a file using the :meth:`fromfile` method).
172
173 .. versionadded:: 3.2
174 :meth:`!fromstring` is renamed to :meth:`frombytes` for clarity.
175
176
177 .. method:: fromfile(f, n, /)
178
179 Read *n* items (as machine values) from the :term:`file object` *f* and append
180 them to the end of the array. If less than *n* items are available,
181 :exc:`EOFError` is raised, but the items that were available are still
182 inserted into the array.
183
184
185 .. method:: fromlist(list, /)
186
187 Append items from the list. This is equivalent to ``for x in list:
188 a.append(x)`` except that if there is a type error, the array is unchanged.
189
190
191 .. method:: fromunicode(ustr, /)
192
193 Extends this array with data from the given Unicode string.
194 The array must have type code ``'u'`` or ``'w'``; otherwise a :exc:`ValueError` is raised.
195 Use ``array.frombytes(unicodestring.encode(enc))`` to append Unicode data to an
196 array of some other type.
197
198
199 .. method:: index(value[, start[, stop]])
200
201 Return the smallest *i* such that *i* is the index of the first occurrence of
202 *value* in the array. The optional arguments *start* and *stop* can be
203 specified to search for *value* within a subsection of the array. Raise
204 :exc:`ValueError` if *value* is not found.
205
206 .. versionchanged:: 3.10
207 Added optional *start* and *stop* parameters.
208
209
210 .. method:: insert(index, value, /)
211
212 Insert a new item *value* in the array before position *index*. Negative
213 values are treated as being relative to the end of the array.
214
215
216 .. method:: pop(index=-1, /)
217
218 Removes the item with the index *i* from the array and returns it. The optional
219 argument defaults to ``-1``, so that by default the last item is removed and
220 returned.
221
222
223 .. method:: remove(value, /)
224
225 Remove the first occurrence of *value* from the array.
226
227
228 .. method:: clear()
229
230 Remove all elements from the array.
231
232 .. versionadded:: 3.13
233
234
235 .. method:: reverse()
236
237 Reverse the order of the items in the array.
238
239
240 .. method:: tobytes()
241
242 Convert the array to an array of machine values and return the bytes
243 representation (the same sequence of bytes that would be written to a file by
244 the :meth:`tofile` method.)
245
246 .. versionadded:: 3.2
247 :meth:`!tostring` is renamed to :meth:`tobytes` for clarity.
248
249
250 .. method:: tofile(f, /)
251
252 Write all items (as machine values) to the :term:`file object` *f*.
253
254
255 .. method:: tolist()
256
257 Convert the array to an ordinary list with the same items.
258
259
260 .. method:: tounicode()
261
262 Convert the array to a Unicode string. The array must have a type ``'u'`` or ``'w'``;
263 otherwise a :exc:`ValueError` is raised. Use ``array.tobytes().decode(enc)`` to
264 obtain a Unicode string from an array of some other type.
265
266
267 The string representation of array objects has the form
268 ``array(typecode, initializer)``.
269 The *initializer* is omitted if the array is empty, otherwise it is
270 a Unicode string if the *typecode* is ``'u'`` or ``'w'``, otherwise it is
271 a list of numbers.
272 The string representation is guaranteed to be able to be converted back to an
273 array with the same type and value using :func:`eval`, so long as the
274 :class:`~array.array` class has been imported using ``from array import array``.
275 Variables ``inf`` and ``nan`` must also be defined if it contains
276 corresponding floating-point values.
277 Examples::
278
279 array('l')
280 array('w', 'hello \u2641')
281 array('l', [1, 2, 3, 4, 5])
282 array('d', [1.0, 2.0, 3.14, -inf, nan])
283
284
285 .. seealso::
286
287 Module :mod:`struct`
288 Packing and unpacking of heterogeneous binary data.
289
290 `NumPy <https://numpy.org/>`_
291 The NumPy package defines another array type.