all Python 3arrayterm
array.array
arrays
A compact mutable array of numbers of one type, set by a type code ('i', 'd', 'B'…); it stores raw values, not objects.
Syntax
array.array(typecode[, initializer])
A list stores pointers to separate int objects (8 bytes per reference plus the object itself), while an array stores bare numbers of itemsize bytes each, so a million ints in 'i' take about 4 MB instead of 30+. The price is strictness: 'i' rejects 1.5 (TypeError) and 'b' rejects 200 (OverflowError). There is no vector maths: a * 2 repeats the array as a list would rather than multiplying the numbers — that is what numpy is for.
Examples
import array, sys
nums = array.array('i', range(1000))
print(nums.itemsize * len(nums)) # → 4000
print(sys.getsizeof(nums) < sys.getsizeof(list(range(1000)))) # → True
print(nums[:3] * 2) # → array('i', [0, 1, 2, 0, 1, 2]) — повтор, а не умножение
import array
a = array.array('b', [1, 2])
try:
a.append(1.5)
except TypeError:
print('дробное не влезет') # → дробное не влезет
try:
a.append(200)
except OverflowError as e:
print(e) # → signed char is greater than maximum
print(array.array('B', b'abc').tolist()) # → [97, 98, 99]
See also
Open in the full glossarydocs.python.orgReport an inaccuracy