Return a NumPy array's shape, ndim, size, itemsize and nbytes as a tuple
Quick Overview
Write a NumPy function that returns an array's shape, number of dimensions, element count, item size and total data bytes as one tuple. It tests knowledge of ndarray attributes, how the dtype sets the width of each element, and why views make nbytes a poor measure of allocated memory.
Return a NumPy array's shape, ndim, size, itemsize and nbytes as a tuple
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Given a NumPy `ndarray` `arr`, return the tuple `(shape, ndim, size, itemsize, nbytes)` describing its layout:
- `shape` is the shape as a tuple.
- `ndim` is the number of dimensions.
- `size` is the total number of elements.
- `itemsize` is the byte size of one element.
- `nbytes` is the total number of data bytes (`size * itemsize`).
The input is always a valid `ndarray`, so no type validation is required.
For example:
```python
arr = np.zeros((2, 3), dtype=np.float64)
describe(arr) # ((2, 3), 2, 6, 8, 48)
```
```hint Look before you compute
Check what the array object already exposes before computing anything. Then ask which of the five values depend on the shape and which depend on the dtype.
```
### What a Strong Answer Covers
- Reads each value from the matching `ndarray` attribute and knows NumPy keeps them consistent with each other
- Explains which fields come from the shape and which come from the dtype
- States the identity `nbytes == size * itemsize` and checks it on the example
- Handles edge cases such as a 0-d array, an empty array and an object array
### Follow-up Questions
- How would `nbytes` differ for a non-contiguous view or a sliced array?
- Why might `itemsize` vary for the same logical values?
- How would you find out how much memory an array really holds when it may be a view of a larger buffer?
Overview: Write a NumPy function that returns an array's shape, number of dimensions, element count, item size and total data bytes as one tuple. It tests knowledge of ndarray attributes, how the dtype sets the width of each element, and why views make nbytes a poor measure of allocated memory.