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 Arrays are :ref:`generic <generics>` over the type of their contents.
110
111 .. audit-event:: array.__new__ typecode,initializer array.array
112
113
114 .. attribute:: typecode
115
116 The typecode character used to create the array.
117
118
119 .. attribute:: itemsize
120
121 The length in bytes of one array item in the internal representation.
122
123
124 .. method:: append(value, /)
125
126 Append a new item with the specified value to the end of the array.
127
128
129 .. method:: buffer_info()
130
131 Return a tuple ``(address, length)`` giving the current memory address and the
132 length in elements of the buffer used to hold array's contents. The size of the
133 memory buffer in bytes can be computed as ``array.buffer_info()[1] *
134 array.itemsize``. This is occasionally useful when working with low-level (and
135 inherently unsafe) I/O interfaces that require memory addresses, such as certain
136 :c:func:`!ioctl` operations. The returned numbers are valid as long as the array
137 exists and no length-changing operations are applied to it.
138
139 .. note::
140
141 When using array objects from code written in C or C++ (the only way to
142 effectively make use of this information), it makes more sense to use the buffer
143 interface supported by array objects. This method is maintained for backward
144 compatibility and should be avoided in new code. The buffer interface is
145 documented in :ref:`bufferobjects`.
146
147
148 .. method:: byteswap()
149
150 "Byteswap" all items of the array. This is only supported for values which are
151 1, 2, 4, or 8 bytes in size; for other types of values, :exc:`RuntimeError` is
152 raised. It is useful when reading data from a file written on a machine with a
153 different byte order.
154
155
156 .. method:: count(value, /)
157
158 Return the number of occurrences of *value* in the array.
159
160
161 .. method:: extend(iterable, /)
162
163 Append items from *iterable* to the end of the array. If *iterable* is another
164 array, it must have *exactly* the same type code; if not, :exc:`TypeError` will
165 be raised. If *iterable* is not an array, it must be iterable and its elements
166 must be the right type to be appended to the array.
167
168
169 .. method:: frombytes(buffer, /)
170
171 Appends items from the :term:`bytes-like object`, interpreting
172 its content as an array of machine values (as if it had been read
173 from a file using the :meth:`fromfile` method).
174
175 .. versionadded:: 3.2
176 :meth:`!fromstring` is renamed to :meth:`frombytes` for clarity.
177
178
179 .. method:: fromfile(f, n, /)
180
181 Read *n* items (as machine values) from the :term:`file object` *f* and append
182 them to the end of the array. If less than *n* items are available,
183 :exc:`EOFError` is raised, but the items that were available are still
184 inserted into the array.
185
186
187 .. method:: fromlist(list, /)
188
189 Append items from the list. This is equivalent to ``for x in list:
190 a.append(x)`` except that if there is a type error, the array is unchanged.
191
192
193 .. method:: fromunicode(ustr, /)
194
195 Extends this array with data from the given Unicode string.
196 The array must have type code ``'u'`` or ``'w'``; otherwise a :exc:`ValueError` is raised.
197 Use ``array.frombytes(unicodestring.encode(enc))`` to append Unicode data to an
198 array of some other type.
199
200
201 .. method:: index(value[, start[, stop]])
202
203 Return the smallest *i* such that *i* is the index of the first occurrence of
204 *value* in the array. The optional arguments *start* and *stop* can be
205 specified to search for *value* within a subsection of the array. Raise
206 :exc:`ValueError` if *value* is not found.
207
208 .. versionchanged:: 3.10
209 Added optional *start* and *stop* parameters.
210
211
212 .. method:: insert(index, value, /)
213
214 Insert a new item *value* in the array before position *index*. Negative
215 values are treated as being relative to the end of the array.
216
217
218 .. method:: pop(index=-1, /)
219
220 Removes the item with the index *i* from the array and returns it. The optional
221 argument defaults to ``-1``, so that by default the last item is removed and
222 returned.
223
224
225 .. method:: remove(value, /)
226
227 Remove the first occurrence of *value* from the array.
228
229
230 .. method:: clear()
231
232 Remove all elements from the array.
233
234 .. versionadded:: 3.13
235
236
237 .. method:: reverse()
238
239 Reverse the order of the items in the array.
240
241
242 .. method:: tobytes()
243
244 Convert the array to an array of machine values and return the bytes
245 representation (the same sequence of bytes that would be written to a file by
246 the :meth:`tofile` method.)
247
248 .. versionadded:: 3.2
249 :meth:`!tostring` is renamed to :meth:`tobytes` for clarity.
250
251
252 .. method:: tofile(f, /)
253
254 Write all items (as machine values) to the :term:`file object` *f*.
255
256
257 .. method:: tolist()
258
259 Convert the array to an ordinary list with the same items.
260
261
262 .. method:: tounicode()
263
264 Convert the array to a Unicode string. The array must have a type ``'u'`` or ``'w'``;
265 otherwise a :exc:`ValueError` is raised. Use ``array.tobytes().decode(enc)`` to
266 obtain a Unicode string from an array of some other type.
267
268
269 The string representation of array objects has the form
270 ``array(typecode, initializer)``.
271 The *initializer* is omitted if the array is empty, otherwise it is
272 a Unicode string if the *typecode* is ``'u'`` or ``'w'``, otherwise it is
273 a list of numbers.
274 The string representation is guaranteed to be able to be converted back to an
275 array with the same type and value using :func:`eval`, so long as the
276 :class:`~array.array` class has been imported using ``from array import array``.
277 Variables ``inf`` and ``nan`` must also be defined if it contains
278 corresponding floating-point values.
279 Examples::
280
281 array('l')
282 array('w', 'hello \u2641')
283 array('l', [1, 2, 3, 4, 5])
284 array('d', [1.0, 2.0, 3.14, -inf, nan])
285
286
287 .. seealso::
288
289 Module :mod:`struct`
290 Packing and unpacking of heterogeneous binary data.
291
292 `NumPy <https://numpy.org/>`_
293 The NumPy package defines another array type.