Array Properties
Problem Statement
Examine and report properties of a NumPy array.
Background
NumPy arrays have useful properties:
- shape: Tuple of dimensions
- dtype: Data type
- size: Total number of elements
- ndim: Number of dimensions
Your Task
Write a function array_info(arr) that returns information about an array.
Output Format
Return a dictionary with:
- "shape": Tuple of dimensions (as list)
- "dtype": Data type as string
- "size": Total elements
- "ndim": Number of dimensions
- "is_matrix": True if 2D, False otherwise
Example:
np.array([[1, 2, 3], [4, 5, 6]])
{'shape': [2, 3], 'dtype': 'int64', 'size': 6, 'ndim': 2, 'is_matrix': True}2 rows × 3 cols = 6 elements, 2D array is a matrix
Constraints:
- dtype output may vary by system (int64, int32, float64, etc.)
- Accept both int64 and int32 as valid integer dtypes
More from NumPy Foundations
Background Knowledge
NumPy arrays are the foundational data structure for numerical computing in Python, enabling efficient storage and manipulation of homogeneous data in multi-dimensional grids. Key properties include shape, a tuple describing the array's dimensions (e.g., (2, 3) for a 2x3 matrix); dtype, the data type of elements (e.g., int64, float32); size, the total count of elements (product of shape dimensions); and ndim, the number of dimensions (length of the shape tuple). These attributes provide metadata without altering the array, supporting vectorized operations that outperform Python lists by avoiding loops and leveraging low-level optimizations.
Understanding these properties is crucial for array creation and basics, as they determine memory layout, broadcasting rules, and compatibility with operations like reshaping or slicing. For instance, a 2D array with ndim=2 behaves like a matrix, enabling linear algebra, while higher ndim supports tensors. Accessing properties is instantaneous (O(1) time), making them ideal for inspection tasks.
Algorithm/Approach
The approach is a direct property inspection pattern: query the array's built-in attributes and package them into a dictionary matching the required format. No computation or iteration is needed—leverage NumPy's metadata accessors to extract values, perform minimal conditional logic for derived flags (e.g., checking if ndim == 2), and ensure output types align with specifications (e.g., convert shape tuple to list).
This pattern scales to any array dimensionality and emphasizes immutability: read-only access preserves the original array while providing structured insights.
Step-by-Step Strategy
- Access core properties: Retrieve arr.shape, arr.dtype, arr.size, and arr.ndim directly from the input array.
- Format shape: Convert the shape tuple to a list (e.g., (2, 3) → [2, 3]).
- Convert dtype: Cast dtype to string (e.g., dtype('int64') → 'int64').
- Check matrix condition: Set is_matrix to True if ndim == 2, else False.
- Assemble dictionary: Return a dict with keys "shape", "dtype", "size", "ndim", and "is_matrix" using the extracted values.
- Test edge cases: Verify with 1D, 3D, empty, and scalar-like arrays to ensure robustness.
Common Pitfalls
- Shape conversion: Forgetting to convert shape (tuple) to list causes type mismatch errors.
- Dtype string: Using str(arr.dtype) may include extra info (e.g., 'int64'); use arr.dtype.name or str(arr.dtype).split('[') for clean output.
- Integer overflow: size is safe for typical arrays, but very large shapes may exceed int limits—NumPy handles this internally.
- Empty arrays: shape=(), size=0, ndim=0 are valid; is_matrix=False.
- Import omission: Ensure import numpy as np and pass a true NumPy array (not list).
Time & Space Complexity
- Time: O(1) – All property accesses are constant-time metadata reads; no loops or computations.
- Space: O(d) where d is ndim (for shape list copy), plus O(1) for the dictionary. Negligible even for high-dimensional arrays, as only metadata is stored.