blob: c7f137d15b4b8608681ff1e54619da832e934766 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`array` --- Efficient arrays of numeric values
2===================================================
3
4.. module:: array
Benjamin Peterson2a691a82008-03-31 01:51:45 +00005 :synopsis: Space efficient arrays of uniformly typed numeric values.
Georg Brandl116aa622007-08-15 14:28:22 +00006
Georg Brandl116aa622007-08-15 14:28:22 +00007.. index:: single: arrays
8
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04009--------------
10
Benjamin Peterson2a691a82008-03-31 01:51:45 +000011This module defines an object type which can compactly represent an array of
Georg Brandl116aa622007-08-15 14:28:22 +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
Meador Inge1c9f0c92011-09-20 19:55:51 -050018+-----------+--------------------+-------------------+-----------------------+-------+
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+-----------+--------------------+-------------------+-----------------------+-------+
Inada Naokid5d9a712020-05-11 15:37:25 +090025| ``'u'`` | wchar_t | Unicode character | 2 | \(1) |
Meador Inge1c9f0c92011-09-20 19:55:51 -050026+-----------+--------------------+-------------------+-----------------------+-------+
27| ``'h'`` | signed short | int | 2 | |
28+-----------+--------------------+-------------------+-----------------------+-------+
29| ``'H'`` | unsigned short | int | 2 | |
30+-----------+--------------------+-------------------+-----------------------+-------+
31| ``'i'`` | signed int | int | 2 | |
32+-----------+--------------------+-------------------+-----------------------+-------+
33| ``'I'`` | unsigned int | int | 2 | |
34+-----------+--------------------+-------------------+-----------------------+-------+
35| ``'l'`` | signed long | int | 4 | |
36+-----------+--------------------+-------------------+-----------------------+-------+
37| ``'L'`` | unsigned long | int | 4 | |
38+-----------+--------------------+-------------------+-----------------------+-------+
Sergey Fedoseeva38e9d12019-08-22 20:28:28 +050039| ``'q'`` | signed long long | int | 8 | |
Meador Inge1c9f0c92011-09-20 19:55:51 -050040+-----------+--------------------+-------------------+-----------------------+-------+
Sergey Fedoseeva38e9d12019-08-22 20:28:28 +050041| ``'Q'`` | unsigned long long | int | 8 | |
Meador Inge1c9f0c92011-09-20 19:55:51 -050042+-----------+--------------------+-------------------+-----------------------+-------+
43| ``'f'`` | float | float | 4 | |
44+-----------+--------------------+-------------------+-----------------------+-------+
45| ``'d'`` | double | float | 8 | |
46+-----------+--------------------+-------------------+-----------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +000047
Meador Inge1c9f0c92011-09-20 19:55:51 -050048Notes:
Georg Brandl9cbb1252009-07-11 10:39:00 +000049
Meador Inge1c9f0c92011-09-20 19:55:51 -050050(1)
Inada Naokid5d9a712020-05-11 15:37:25 +090051 It can be 16 bits or 32 bits depending on the platform.
Victor Stinner62bb3942012-08-06 00:46:05 +020052
Inada Naokid5d9a712020-05-11 15:37:25 +090053 .. versionchanged:: 3.9
54 ``array('u')`` now uses ``wchar_t`` as C type instead of deprecated
55 ``Py_UNICODE``. This change doesn't affect to its behavior because
56 ``Py_UNICODE`` is alias of ``wchar_t`` since Python 3.3.
Stefan Krah029780b2012-08-24 20:14:12 +020057
58 .. deprecated-removed:: 3.3 4.0
59
Inada Naokid5d9a712020-05-11 15:37:25 +090060
Georg Brandl116aa622007-08-15 14:28:22 +000061The actual representation of values is determined by the machine architecture
62(strictly speaking, by the C implementation). The actual size can be accessed
Georg Brandlba956ae2007-11-29 17:24:34 +000063through the :attr:`itemsize` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +000064
65The module defines the following type:
66
67
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +000068.. class:: array(typecode[, initializer])
Georg Brandl116aa622007-08-15 14:28:22 +000069
Alexandre Vassalotti711ed4a2009-07-17 10:42:05 +000070 A new array whose items are restricted by *typecode*, and initialized
Ezio Melottic228e962013-05-04 18:06:34 +030071 from the optional *initializer* value, which must be a list, a
72 :term:`bytes-like object`, or iterable over elements of the
Guido van Rossum98297ee2007-11-06 21:34:58 +000073 appropriate type.
Georg Brandl116aa622007-08-15 14:28:22 +000074
Georg Brandl116aa622007-08-15 14:28:22 +000075 If given a list or string, the initializer is passed to the new array's
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +000076 :meth:`fromlist`, :meth:`frombytes`, or :meth:`fromunicode` method (see below)
Georg Brandl116aa622007-08-15 14:28:22 +000077 to add initial items to the array. Otherwise, the iterable initializer is
78 passed to the :meth:`extend` method.
79
Steve Dower44f91c32019-06-27 10:47:59 -070080 .. audit-event:: array.__new__ typecode,initializer array.array
Georg Brandl116aa622007-08-15 14:28:22 +000081
Guido van Rossum98297ee2007-11-06 21:34:58 +000082.. data:: typecodes
83
84 A string with all available type codes.
85
Georg Brandl116aa622007-08-15 14:28:22 +000086Array objects support the ordinary sequence operations of indexing, slicing,
87concatenation, and multiplication. When using slice assignment, the assigned
88value must be an array object with the same type code; in all other cases,
89:exc:`TypeError` is raised. Array objects also implement the buffer interface,
Serhiy Storchakae5ea1ab2016-05-18 13:54:54 +030090and may be used wherever :term:`bytes-like objects <bytes-like object>` are supported.
Georg Brandl116aa622007-08-15 14:28:22 +000091
92The following data items and methods are also supported:
93
Georg Brandl116aa622007-08-15 14:28:22 +000094.. attribute:: array.typecode
95
96 The typecode character used to create the array.
97
98
99.. attribute:: array.itemsize
100
101 The length in bytes of one array item in the internal representation.
102
103
104.. method:: array.append(x)
105
106 Append a new item with value *x* to the end of the array.
107
108
109.. method:: array.buffer_info()
110
111 Return a tuple ``(address, length)`` giving the current memory address and the
112 length in elements of the buffer used to hold array's contents. The size of the
113 memory buffer in bytes can be computed as ``array.buffer_info()[1] *
114 array.itemsize``. This is occasionally useful when working with low-level (and
115 inherently unsafe) I/O interfaces that require memory addresses, such as certain
Georg Brandl60203b42010-10-06 10:11:56 +0000116 :c:func:`ioctl` operations. The returned numbers are valid as long as the array
Georg Brandl116aa622007-08-15 14:28:22 +0000117 exists and no length-changing operations are applied to it.
118
119 .. note::
120
121 When using array objects from code written in C or C++ (the only way to
122 effectively make use of this information), it makes more sense to use the buffer
123 interface supported by array objects. This method is maintained for backward
124 compatibility and should be avoided in new code. The buffer interface is
125 documented in :ref:`bufferobjects`.
126
127
128.. method:: array.byteswap()
129
130 "Byteswap" all items of the array. This is only supported for values which are
131 1, 2, 4, or 8 bytes in size; for other types of values, :exc:`RuntimeError` is
132 raised. It is useful when reading data from a file written on a machine with a
133 different byte order.
134
135
136.. method:: array.count(x)
137
138 Return the number of occurrences of *x* in the array.
139
140
141.. method:: array.extend(iterable)
142
143 Append items from *iterable* to the end of the array. If *iterable* is another
144 array, it must have *exactly* the same type code; if not, :exc:`TypeError` will
145 be raised. If *iterable* is not an array, it must be iterable and its elements
146 must be the right type to be appended to the array.
147
Georg Brandl116aa622007-08-15 14:28:22 +0000148
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +0000149.. method:: array.frombytes(s)
150
151 Appends items from the string, interpreting the string as an array of machine
152 values (as if it had been read from a file using the :meth:`fromfile` method).
153
154 .. versionadded:: 3.2
155 :meth:`fromstring` is renamed to :meth:`frombytes` for clarity.
156
157
Georg Brandl116aa622007-08-15 14:28:22 +0000158.. method:: array.fromfile(f, n)
159
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000160 Read *n* items (as machine values) from the :term:`file object` *f* and append
161 them to the end of the array. If less than *n* items are available,
162 :exc:`EOFError` is raised, but the items that were available are still
Adorilson Bezerrabd25bcd2021-04-26 11:19:21 -0300163 inserted into the array.
Georg Brandl116aa622007-08-15 14:28:22 +0000164
165
166.. method:: array.fromlist(list)
167
168 Append items from the list. This is equivalent to ``for x in list:
169 a.append(x)`` except that if there is a type error, the array is unchanged.
170
171
Georg Brandl116aa622007-08-15 14:28:22 +0000172.. method:: array.fromunicode(s)
173
174 Extends this array with data from the given unicode string. The array must
175 be a type ``'u'`` array; otherwise a :exc:`ValueError` is raised. Use
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +0000176 ``array.frombytes(unicodestring.encode(enc))`` to append Unicode data to an
Georg Brandl116aa622007-08-15 14:28:22 +0000177 array of some other type.
178
179
Zackery Spytzafd12652021-04-02 09:28:35 -0600180.. method:: array.index(x[, start[, stop]])
Georg Brandl116aa622007-08-15 14:28:22 +0000181
182 Return the smallest *i* such that *i* is the index of the first occurrence of
Zackery Spytzafd12652021-04-02 09:28:35 -0600183 *x* in the array. The optional arguments *start* and *stop* can be
184 specified to search for *x* within a subsection of the array. Raise
185 :exc:`ValueError` if *x* is not found.
Georg Brandl116aa622007-08-15 14:28:22 +0000186
Zackery Spytzafd12652021-04-02 09:28:35 -0600187 .. versionchanged:: 3.10
188 Added optional *start* and *stop* parameters.
Georg Brandl116aa622007-08-15 14:28:22 +0000189
190.. method:: array.insert(i, x)
191
192 Insert a new item with value *x* in the array before position *i*. Negative
193 values are treated as being relative to the end of the array.
194
195
196.. method:: array.pop([i])
197
198 Removes the item with the index *i* from the array and returns it. The optional
199 argument defaults to ``-1``, so that by default the last item is removed and
200 returned.
201
202
Georg Brandl116aa622007-08-15 14:28:22 +0000203.. method:: array.remove(x)
204
205 Remove the first occurrence of *x* from the array.
206
207
208.. method:: array.reverse()
209
210 Reverse the order of the items in the array.
211
212
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +0000213.. method:: array.tobytes()
214
215 Convert the array to an array of machine values and return the bytes
216 representation (the same sequence of bytes that would be written to a file by
217 the :meth:`tofile` method.)
218
219 .. versionadded:: 3.2
220 :meth:`tostring` is renamed to :meth:`tobytes` for clarity.
221
222
Georg Brandl116aa622007-08-15 14:28:22 +0000223.. method:: array.tofile(f)
224
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000225 Write all items (as machine values) to the :term:`file object` *f*.
Georg Brandl116aa622007-08-15 14:28:22 +0000226
227
228.. method:: array.tolist()
229
230 Convert the array to an ordinary list with the same items.
231
232
Georg Brandl116aa622007-08-15 14:28:22 +0000233.. method:: array.tounicode()
234
235 Convert the array to a unicode string. The array must be a type ``'u'`` array;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +0000236 otherwise a :exc:`ValueError` is raised. Use ``array.tobytes().decode(enc)`` to
Georg Brandl116aa622007-08-15 14:28:22 +0000237 obtain a unicode string from an array of some other type.
238
239
Georg Brandl116aa622007-08-15 14:28:22 +0000240When an array object is printed or converted to a string, it is represented as
241``array(typecode, initializer)``. The *initializer* is omitted if the array is
Georg Brandld2aa7e62008-12-06 08:12:11 +0000242empty, otherwise it is a string if the *typecode* is ``'u'``, otherwise it is a
Georg Brandl116aa622007-08-15 14:28:22 +0000243list of numbers. The string is guaranteed to be able to be converted back to an
244array with the same type and value using :func:`eval`, so long as the
Serhiy Storchakaee1b01a2016-12-02 23:13:53 +0200245:class:`~array.array` class has been imported using ``from array import array``.
Georg Brandl116aa622007-08-15 14:28:22 +0000246Examples::
247
248 array('l')
Georg Brandld2aa7e62008-12-06 08:12:11 +0000249 array('u', 'hello \u2641')
Georg Brandl116aa622007-08-15 14:28:22 +0000250 array('l', [1, 2, 3, 4, 5])
251 array('d', [1.0, 2.0, 3.14])
252
253
254.. seealso::
255
256 Module :mod:`struct`
257 Packing and unpacking of heterogeneous binary data.
258
259 Module :mod:`xdrlib`
260 Packing and unpacking of External Data Representation (XDR) data as used in some
261 remote procedure call systems.
262
Andre Delfinoc8bb2412020-10-01 20:22:14 -0300263 `NumPy <https://numpy.org/>`_
264 The NumPy package defines another array type.
Georg Brandl116aa622007-08-15 14:28:22 +0000265