array
— Efficient arrays of numeric values¶
This module defines an object type which can compactly represent an array ofbasic values: characters, integers, floating-point numbers. Arrays are sequencetypes and behave very much like lists, except that the type of objects stored inthem is constrained. The type is specified at object creation time by using atype code, which is a single character. The following type codes aredefined:
Type code | C Type | Python Type | Minimum size in bytes | Notes |
---|---|---|---|---|
| signed char | int | 1 | |
| unsigned char | int | 1 | |
| wchar_t | Unicode character | 2 | (1) |
| Py_UCS4 | Unicode character | 4 | |
| signed short | int | 2 | |
| unsigned short | int | 2 | |
| signed int | int | 2 | |
| unsigned int | int | 2 | |
| signed long | int | 4 | |
| unsigned long | int | 4 | |
| signed long long | int | 8 | |
| unsigned long long | int | 8 | |
| float | float | 4 | |
| double | float | 8 |
Notes:
It can be 16 bits or 32 bits depending on the platform.
Changed in version 3.9:
array('u')
now useswchar_t
as C type instead of deprecatedPy_UNICODE
. This change doesn’t affect its behavior becausePy_UNICODE
is alias ofwchar_t
since Python 3.3.Deprecated since version 3.3, will be removed in version 3.16:Please migrate to
'w'
typecode.
The actual representation of values is determined by the machine architecture(strictly speaking, by the C implementation). The actual size can be accessedthrough thearray.itemsize
attribute.
The module defines the following item:
- array.typecodes¶
A string with all available type codes.
The module defines the following type:
- classarray.array(typecode[,initializer])¶
A new array whose items are restricted bytypecode, and initializedfrom the optionalinitializer value, which must be a
bytes
orbytearray
object, a Unicode string, or iterable over elementsof the appropriate type.If given a
bytes
orbytearray
object, the initializeris passed to the new array’sfrombytes()
method;if given a Unicode string, the initializer is passed to thefromunicode()
method;otherwise, the initializer’s iterator is passed to theextend()
methodto add initial items to the array.Array objects support the ordinary sequence operations of indexing, slicing,concatenation, and multiplication. When using slice assignment, the assignedvalue must be an array object with the same type code; in all other cases,
TypeError
is raised. Array objects also implement the buffer interface,and may be used whereverbytes-like objects are supported.Raises anauditing event
array.__new__
with argumentstypecode
,initializer
.- typecode¶
The typecode character used to create the array.
- itemsize¶
The length in bytes of one array item in the internal representation.
- append(x)¶
Append a new item with valuex to the end of the array.
- buffer_info()¶
Return a tuple
(address,length)
giving the current memory address and thelength in elements of the buffer used to hold array’s contents. The size of thememory buffer in bytes can be computed asarray.buffer_info()[1]*array.itemsize
. This is occasionally useful when working with low-level (andinherently unsafe) I/O interfaces that require memory addresses, such as certainioctl()
operations. The returned numbers are valid as long as the arrayexists and no length-changing operations are applied to it.Note
When using array objects from code written in C or C++ (the only way toeffectively make use of this information), it makes more sense to use the bufferinterface supported by array objects. This method is maintained for backwardcompatibility and should be avoided in new code. The buffer interface isdocumented inBuffer Protocol.
- byteswap()¶
“Byteswap” all items of the array. This is only supported for values which are1, 2, 4, or 8 bytes in size; for other types of values,
RuntimeError
israised. It is useful when reading data from a file written on a machine with adifferent byte order.
- count(x)¶
Return the number of occurrences ofx in the array.
- extend(iterable)¶
Append items fromiterable to the end of the array. Ifiterable is anotherarray, it must haveexactly the same type code; if not,
TypeError
willbe raised. Ifiterable is not an array, it must be iterable and its elementsmust be the right type to be appended to the array.
- frombytes(buffer)¶
Appends items from thebytes-like object, interpretingits content as an array of machine values (as if it had been readfrom a file using the
fromfile()
method).Added in version 3.2:
fromstring()
is renamed tofrombytes()
for clarity.
- fromfile(f,n)¶
Readn items (as machine values) from thefile objectf and appendthem to the end of the array. If less thann items are available,
EOFError
is raised, but the items that were available are stillinserted into the array.
- fromlist(list)¶
Append items from the list. This is equivalent to
forxinlist:a.append(x)
except that if there is a type error, the array is unchanged.
- fromunicode(s)¶
Extends this array with data from the given Unicode string.The array must have type code
'u'
or'w'
; otherwise aValueError
is raised.Usearray.frombytes(unicodestring.encode(enc))
to append Unicode data to anarray of some other type.
- index(x[,start[,stop]])¶
Return the smallesti such thati is the index of the first occurrence ofx in the array. The optional argumentsstart andstop can bespecified to search forx within a subsection of the array. Raise
ValueError
ifx is not found.Changed in version 3.10:Added optionalstart andstop parameters.
- insert(i,x)¶
Insert a new item with valuex in the array before positioni. Negativevalues are treated as being relative to the end of the array.
- pop([i])¶
Removes the item with the indexi from the array and returns it. The optionalargument defaults to
-1
, so that by default the last item is removed andreturned.
- remove(x)¶
Remove the first occurrence ofx from the array.
- clear()¶
Remove all elements from the array.
Added in version 3.13.
- reverse()¶
Reverse the order of the items in the array.
- tobytes()¶
Convert the array to an array of machine values and return the bytesrepresentation (the same sequence of bytes that would be written to a file bythe
tofile()
method.)Added in version 3.2:
tostring()
is renamed totobytes()
for clarity.
- tofile(f)¶
Write all items (as machine values) to thefile objectf.
- tolist()¶
Convert the array to an ordinary list with the same items.
- tounicode()¶
Convert the array to a Unicode string. The array must have a type
'u'
or'w'
;otherwise aValueError
is raised. Usearray.tobytes().decode(enc)
toobtain a Unicode string from an array of some other type.
The string representation of array objects has the formarray(typecode,initializer)
.Theinitializer is omitted if the array is empty, otherwise it isa Unicode string if thetypecode is'u'
or'w'
, otherwise it isa list of numbers.The string representation is guaranteed to be able to be converted back to anarray with the same type and value usingeval()
, so long as thearray
class has been imported usingfromarrayimportarray
.Variablesinf
andnan
must also be defined if it containscorresponding floating-point values.Examples:
array('l')array('w','hello\u2641')array('l',[1,2,3,4,5])array('d',[1.0,2.0,3.14,-inf,nan])