For programmers who have used other languages, Python lists have many of the properties of an array, which in C++ or Java is a collection of consecutive memory locations that contain the same type of value. Lists may be designed to make operations such as concatenation efficient, which means that a list may not be the most efficient way to store things. A Python array is a class that mimics the array type of other languages and offers efficiency in storage, exchanging that for flexibility.
Only certain types can be stored in an array, and the type of the array is specified when it is created. For example,
data = array(‘f’, [12.8, 5.4, 8.0, 8.0, 9.21, 3.14])
creates an array of 6 floating point numbers; the type is indicated by the “f” as the first parameter to the constructor. This concept is unlike the Python norm of types being dynamic and malleable. An array is an array of one kind of thing, and an array can only hold a restricted set of types.
The type code, the first parameter to the constructor, can have one of 13 values, but the most commonly used ones are as follows:
‘b’ C++ char type
‘B’ C++ unsigned char type
‘i’: C++ int type
‘l’: C++ long type
T: C++ float type
‘d’: C++ double type
Arrays are class objects and are provided in the built-in module array, which must be imported:
from array import array
An array is a sequence type, and it has the basic properties and operations that Python provides for all the sequence types. Array elements can be assigned to and can be used in expressions, and arrays can be searched and extended like other sequences. There are some features of arrays that are unique:
frombytes (s) The string argument s is converted into byte sequences and appended to the array.
fromfile(f, num) Read num items from the file object f and append them. An integer, for example, is one item.
fromlist (x) Append the elements from the list x to the array.
tobytes() Convert the array into a sequence of bytes in machine rep resentation.
tofile(f) Write the array as a sequence of bytes to the file f.
In most cases, arrays are used to speed up numerical operations, but they can also be used to access the underlying representations of numbers.
Source: Parker James R. (2021), Python: An Introduction to Programming, Mercury Learning and Information; Second edition.