array Module Stores Typed Compact Sequences
array.array stores numbers in raw machine width by typecode, enforces element types with TypeError, and converts through tobytes and frombytes.
Code
from array import array
# typecode 'q' 是 8 字节有符号整数,'d' 是双精度浮点
readings = array("q", [120, 250, 37, 998])
print("itemsize:", readings.itemsize, "count:", readings.buffer_info()[1])
# 行为像 list:索引、追加、切片都在,但元素必须匹配类型码
readings.append(1010)
print(readings[2], list(readings[1:3]))
try:
readings.append("not a number")
except TypeError as err:
print("rejected:", err)
# tobytes/frombytes 与二进制格式直通;tolist 转普通列表
blob = readings.tobytes()
copy = array("q")
copy.frombytes(blob)
print(copy == readings, len(blob))
floats = array("d", [0.5, 1.5, 2.5])
print("float itemsize:", floats.itemsize)Output
Captured from a sandboxed run of this snippet in the build pipeline.
itemsize: 8 count: 4
37 [250, 37]
rejected: 'str' object cannot be interpreted as an integer
True 40
float itemsize: 8How the snippet works
Everything borrowed from array is visible in one line: array.
The demo data lives in module-level bindings: readings, blob, copy, floats.
Watch out for
- External dependency:
array— install it before running the snippet.
Applying it
Running the file prints labeled results such as itemsize:, rejected:, float itemsize: — each operation’s effect is visible in the output.
Statements that matter
except TypeError as err:
print("rejected:", err)
Interactive Tools for This Topic
Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Are there any imports to resolve outside the language?
- No. Every import resolves against the language's own modules. Its state lives in module-level bindings: `readings`, `blob`, `copy`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.