Overview of Array Attributes
| Attribute | Meaning | Example | Output |
|---|---|---|---|
ndim |
Number of dimensions | a.ndim |
2 |
shape |
Size of each dimension | a.shape |
(2, 3) |
size |
Total number of elements | a.size |
6 |
dtype |
Data type of elements | a.dtype |
int64 |
itemsize |
Bytes used by one element | a.itemsize |
8 |
nbytes |
Total bytes used | a.nbytes |
48 |
1. ndim
Tells you how many dimensions the array has.
a.ndim
# Output: 2
Examples:
np.array([1, 2, 3]).ndim
# Output: 1
np.array([[1, 2], [3, 4]]).ndim
# Output: 2
np.array([[[1, 2], [3, 4]]]).ndim
# Output: 3
2. shape
Tells you the size of each dimension.
a.shape
# Output: (2, 3)
Meaning: 2 rows, 3 columns.
For example:
x = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
print(x.shape)
# Output: (3, 3)
3. size
Returns the total number of elements.
a.size
# Output: 6
Because: 2 rows × 3 columns = 6 total elements.
4. dtype
Returns the data type of elements.
a.dtype
# Possible outputs: int64, float64, bool, str
Example:
x = np.array([10, 20, 30])
print(x.dtype)
5. itemsize
Returns the number of bytes occupied by one element.
a.itemsize
For example, if the array uses int64, the output is 8 bytes because 64 bits ÷ 8 = 8 bytes.
6. nbytes
Returns the total memory consumed by the array elements.
a.nbytes
For our array: 6 elements × 8 bytes = 48 bytes. So:
print(a.nbytes)
# Output: 48
⭐ Quick Summary to Remember
A very useful way to teach and remember these attributes:
ndim→ How many dimensions?shape→ What is the size? (rows, columns, ...)size→ How many elements in total?dtype→ What data type?itemsize→ How much memory per element?nbytes→ How much total memory?