/Curriculum/AdvancedData Types

42. Structured Arrays & Record TypesAdvanced

Define C-style struct records with named fields and heterogeneous dtypes.

15 mins

Concept Overview

Structured arrays allow storing complex C-style records with named fields (e.g. `name`, `age`, `salary`) with different data types inside a single contiguous array buffer.

Hardware Mental Model

A structured array is a C-struct in Python: each row is a record holding multiple typed columns stored side-by-side in continuous memory.

Key Concepts (1)Click snippet to load in editor

Fields are defined with `(field_name, format_code)`: `'U10'` (Unicode string 10 chars), `'i4'` (int32), `'f8'` (float64).

dt = np.dtype([('id', 'i4'), ('score', 'f8')])

⚠ Common Mistakes & Pitfalls

Avoid these frequent beginner syntax and logic traps
❌ Incorrect:students[0]['gpa'] # Row-first lookup
✓ Correct:students['gpa'][0] # Column-first lookup (much faster in NumPy)

Accessing by column `students['gpa']` returns a contiguous vector, which is faster and vectorized.

Pro Tip: Access column fields directly: `students['name']`.

📌 Quick Revision

Core takeaway points from this topic
Structured arrays hold heterogeneous typed records in contiguous memory.
`np.dtype([('field', 'type'), ...])`: Defines record schema.
`arr['field_name']`: Accesses column vector.
`np.sort(arr, order='field')`: Sorts records by specified field.
Editor: 42. Structured Arrays & Record Types
Python ● Ready
Initializing Python IDE...
Ctrl+Enter
Execution Result
Click "RUN CODE" to execute and inspect array state

🎯 Try It Yourself: Practice Challenge

Hands-on Mode

Solve the objective below using NumPy vectorized syntax

Objective:Query Structured Array Field

Define `dt = np.dtype([('name', 'U10'), ('age', 'i4')])`, create `arr = np.array([('Alice', 25)], dtype=dt)`, and print `arr['name']`.

Expected Output Target:['Alice']
Practice Workspace
Python ● Ready
Initializing Python IDE...
Ctrl+Enter
Execution Result
Click "RUN CODE" to execute and inspect array state