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