Challenge - 5 Problems
Field Access Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Accessing a single field by name in a structured NumPy array
What is the output of this code snippet?
NumPy
import numpy as np arr = np.array([(1, 2.0), (3, 4.0)], dtype=[('x', 'i4'), ('y', 'f4')]) result = arr['y'] print(result)
Attempts:
2 left
💡 Hint
Accessing a field by name returns an array of that field's values.
✗ Incorrect
The code creates a structured array with fields 'x' and 'y'. Accessing arr['y'] returns the values of the 'y' field as a float array.
❓ data_output
intermediate2:00remaining
Shape of field extracted from structured array
Given this structured array, what is the shape of the extracted field 'b'?
NumPy
import numpy as np arr = np.array([(1, (2, 3)), (4, (5, 6))], dtype=[('a', 'i4'), ('b', 'i4', (2,))]) field_b = arr['b'] print(field_b.shape)
Attempts:
2 left
💡 Hint
The field 'b' is a 2-element integer array per record, and there are 2 records.
✗ Incorrect
Each record has a field 'b' which is an array of shape (2,). Since there are 2 records, the extracted field has shape (2, 2).
🔧 Debug
advanced2:00remaining
Identify the error when accessing a non-existent field
What error does this code raise?
NumPy
import numpy as np arr = np.array([(1, 2)], dtype=[('x', 'i4'), ('y', 'i4')]) print(arr['z'])
Attempts:
2 left
💡 Hint
Accessing a field by a name not in the dtype raises a KeyError.
✗ Incorrect
The structured array does not have a field named 'z', so accessing arr['z'] raises a KeyError.
🚀 Application
advanced2:00remaining
Extracting multiple fields and combining them
Given this structured array, which option correctly creates a new array combining fields 'name' and 'age' as a list of tuples?
NumPy
import numpy as np arr = np.array([('Alice', 25), ('Bob', 30)], dtype=[('name', 'U10'), ('age', 'i4')])
Attempts:
2 left
💡 Hint
Use zip to pair elements from two arrays into tuples.
✗ Incorrect
Using zip on arr['name'] and arr['age'] pairs each name with its age, then list converts it to a list of tuples.
🧠 Conceptual
expert2:00remaining
Understanding memory layout when accessing fields by name
When you access a field by name in a structured NumPy array, what best describes the memory layout of the returned array?
Attempts:
2 left
💡 Hint
Accessing a field returns a view, not a copy, unless explicitly copied.
✗ Incorrect
Accessing a field by name returns a view into the original array's memory, so changes to the field affect the original array.