Back
+15 XP
Concept

Fast Homogeneous Arrays with the array Module

Python `list` stores pointers to heap objects. The `array.array` module packs primitive C data types contiguously, cutting memory consumption by up to 75% 📐.

python
import array

# 'i' = signed 32-bit integer:
numbers = array.array('i', [10, 20, 30, 40])
numbers.append(50)

print(numbers)               # array('i', [10, 20, 30, 40, 50]) 📐
print(numbers.itemsize)      # 4 bytes per item (pure C integer) ⚡

# 88. Fast Homogeneous Arrays with the array Module Python `list` stores pointers to heap objects. The `array.array` module packs primitive C data types contiguously, cutting memory consumption by up to 75% 📐. ```python import array # 'i' = signed 32-bit integer: numbers = array.array('i', [10, 20, 30, 40]) numbers.append(50) print(numbers) # array('i', [10, 20, 30, 40, 50]) 📐 print(numbers.itemsize) # 4 bytes per item (pure C integer) ⚡ ``` Unlike lists which store 8-byte pointer addresses pointing to 28-byte `PyLongObject` structs, `array` stores raw contiguous C numbers without pointer overhead! 📐 --- ### Question How does `array.array` save significant memory compared to a standard Python `list`? 🧠 - [ ] a. It stores contiguous primitive C values without wrapper object pointers 📐 - [ ] b. It deletes numbers after reading them once - [ ] c. It uses 1-bit integers exclusively - [ ] d. It forces Python to swap items to virtual disk memory --- ### Challenge Import `array`. Create an array of 32-bit signed ints (`'i'`) with values `[1, 2, 3]`. Append `4`. Print `numbers.tolist()`. 🎯 <details> <summary>Solution</summary> ```python import array numbers = array.array("i", [1, 2, 3]) numbers.append(4) print(numbers.tolist()) ``` </details>

Checkpoint

How does `array.array` save significant memory compared to a standard Python `list`? 🧠

Practice

Import `array`. Create an array of 32-bit signed ints (`'i'`) with values `[1, 2, 3]`. Append `4`. Print `numbers.tolist()`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks