Array Attributes Practice Problem
This data science coding problem helps you practice Array Creation & Attributes, array attributes, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Array Creation & Attributes.
- Problem ID: 45
- Problem key: 45-array-attributes
- URL: https://datacrack.app/solve/45-array-attributes
- Difficulty: easy
- Topic: Array Creation & Attributes
- Module: NumPy Foundations
Problem Statement
# 🧩 Array Attributes
---
### 🎯 Goal
Before you can do anything useful with a NumPy array, you need to understand its **shape, dimensions, size, and dtype**. Mismatched shapes cause the most common NumPy errors — this problem builds the mental model to prevent them.
---
### 🔍 The Four Essential Attributes
| Attribute | What It Tells You | Example |
|:----------|:-----------------|:--------|
| `.shape` | Tuple of dimensions | `(3, 4)` → 3 rows, 4 cols |
| `.ndim` | Number of dimensions | `2` for a matrix, `1` for a vector |
| `.size` | Total number of elements | `3 × 4 = 12` |
| `.dtype` | Data type of elements | `int64`, `float64`, `bool` |
---
### 💻 Task
Implement `array_attributes(data)` that creates a NumPy array and returns its attributes.
---
### 📥 Input
- `data`: a nested Python list (1D, 2D, or 3D)
### 📤 Output
A dictionary with keys: `"shape"`, `"ndim"`, `"size"`, `"dtype"` (dtype as a string like `"int64"`)
---
### 🧩 Starter Code
```python
import numpy as np
def array_attributes(data):
"""
Return the shape, ndim, size, and dtype of a NumPy array.
Args:
data (list): Nested Python list (any depth)
Returns:
dict: {"shape", "ndim", "size", "dtype"}
"""
arr = np.array(data)
# 🧠 TODO: Return a dict with the four attributes
# Hint: arr.shape is a tuple — convert to list for JSON compatibility
# Hint: str(arr.dtype) converts dtype to a string like "int64"
pass
```
---
### 💡 Example
```python
array_attributes([[1, 2, 3], [4, 5, 6]])
# Expected: {"shape": [2, 3], "ndim": 2, "size": 6, "dtype": "int64"}
```
---
### 🔑 Key Concepts
- `arr.shape` returns a **tuple** — convert to list with `list(arr.shape)`
- `str(arr.dtype)` converts the dtype object to a readable string
- `arr.ndim` = `len(arr.shape)`
- `arr.size` = product of all dimensions = `np.prod(arr.shape)`Starter Code
import numpy as np
def array_attributes(data):
"""
Return the shape, ndim, size, and dtype of a NumPy array.
Args:
data (list): Nested Python list (any depth)
Returns:
dict: {"shape", "ndim", "size", "dtype"}
"""
arr = np.array(data)
# 🧠 TODO: Return a dict with the four attributes
# Hint: arr.shape is a tuple — convert to list for JSON compatibility
# Hint: str(arr.dtype) converts dtype to a string like "int64"
pass