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