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