array and memoryview: packed data and zero-copy windows
sys.getsizeof numbers differ between 32-bit (this browser) and 64-bit desktops, so the example compares sizes instead of printing them.
A Python list holds pointers to separate objects, while NumPy, array and memoryview use one contiguous block of raw C data that is shared through the buffer protocol. That layout, compiled loops and releasing the GIL in native code are why NumPy is fast.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Create an array('h', [1, 2, 3]) and print its item size, the number of bytes in tobytes() and its sum.
Take a bytes object b"abcdef", build a memoryview, print the bytes of the slice [1:3], whether view.obj is the original object and the length of the view.
Show that memoryview(b"\x01\x00\x02\x00").cast("H") reads the same four bytes as two 16-bit numbers.
Explain it without notes
Give three reasons a NumPy operation is faster than the equivalent Python loop.
What is the buffer protocol, and what does memoryview do with it?
Why does a Python list of a million floats use so much more memory than a NumPy array?
How can native code make multi-threaded Python faster, if the GIL exists?
Expected output
typecode: i item size: 4 bytes
raw bytes: b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00'
buffer_info length: 4
list holds pointers to objects, array holds raw numbers
getsizeof(list) alone counts only the pointers, so add the int objects
array is smaller than list plus its ints: True
array storage = 1000 * itemsize: True
TypeError: 'float' object cannot be interpreted as an integer
OverflowError: Python int too large to convert to C long
copy: b'cde'
view: b'Xde'
data after writing through the view: bytearray(b'abXYefgh')
format: i itemsize: 4 shape: (3,)
as bytes: [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]