Labs ICT
โญ Pro Login

Array Attributes

Shape, size, dtype โ€” understanding your arrays.

2 min read | NumPy Tutorial
โญ

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

Array Attributes

Every NumPy array comes with useful metadata. Think of it like checking the specs of a car before buying it. These attributes tell you everything about your array.

Shape - The Dimensions

Shape tells you the size of each dimension. It's a tuple that's super important for understanding your data.


import numpy as np

arr_1d = np.array([1, 2, 3, 4, 5])
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])

print(f"1D Shape: {arr_1d.shape}")
print(f"2D Shape: {arr_2d.shape}")
    

For 1D, shape is (5,) - note the comma. For 2D, it's (2, 3) meaning 2 rows, 3 columns.

Size & Ndim

Size gives total elements, ndim gives number of dimensions.


import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])
print(f"Size: {arr.size}")
print(f"Dimensions: {arr.ndim}")
    

Here is the thing - size is just the product of all shape values. 2 * 3 = 6.

Dtype - Data Type

Every array has a dtype that tells you what type of data it holds.


import numpy as np

int_arr = np.array([1, 2, 3])
float_arr = np.array([1.0, 2.0, 3.0])

print(f"Int dtype: {int_arr.dtype}")
print(f"Float dtype: {float_arr.dtype}")
    

Common dtypes: int32, int64, float32, float64, bool, string_

Itemsize - Memory per Element

Itemsize tells you how many bytes each element uses.


import numpy as np

int_arr = np.array([1, 2, 3])
float_arr = np.array([1.0, 2.0, 3.0])

print(f"Int itemsize: {int_arr.itemsize} bytes")
print(f"Float itemsize: {float_arr.itemsize} bytes")
    

One thing that confused me at first was why itemsize matters. It affects memory usage and performance. Larger dtypes use more memory.

Key Takeaways

  • shape shows dimensions as a tuple
  • size gives total number of elements
  • ndim shows number of dimensions
  • dtype shows data type, itemsize shows bytes per element

๐Ÿงช Quick Quiz

Which attribute returns the number of dimensions?