Array¶

I switched to Python from languages that are closer to hardware (C/C++, I even programmed in assembly at some point) and was initially somewhat surprised that regular arrays, where everything sits so conveniently in its place, are used relatively rarely. In Python, an array is not the default data structure and is only used in cases where structure size and processing speed become crucial factors. However, on the other hand, if you're looking towards NumPy and Pandas (touched upon briefly below) and want to work with data quickly, then arrays are your everything.

An array stores variables of only a specific type, therefore, unlike a list, it doesn't require creating a new object for each new variable and outperforms lists in terms of size and access speed. You could say it's a thin wrapper around C arrays.

It's important to distinguish between array ("plain" array, mutable), bytes (immutable array containing only bytes, a legacy from Python 2's str), and bytearray (mutable byte array).

In [8]:
from array import array

a1 = array('l', [1, 2, 3, -4])
a2 = array('b', b'1234567890')
b = bytes(a2)

print(a1)
print(a2[0])
print(b)

print(a1.index(-4))  # Returns the index of the element or raises a ValueError
array('l', [1, 2, 3, -4])
49
b'1234567890'
3