Menu
×
×
PYTHON FOR DJANGO DJANGO FOR BEGINNERS DJANGO SPECIFICS PAYMENT INTEGRATION API BASICS NUMPY FOR ML Roadmap
     ❯   

NUMPY FUNDAMENTALS

Array Attributes and Array Indexing and Slicing

×

Share this Topic

Share Via:

Thank you for sharing!


Array Attributes

NumPy arrays have several attributes that provide important information about their properties.

# Creating a sample NumPy array

arr = np.array([[10, 20, 30], [40, 50, 60]])
print("Array:\n", arr)
print("Shape of array:", arr.shape)
# Returns (rows, columns)
print("Size of array:", arr.size)
# Returns total number of elements
print("Number of dimensions:", arr.ndim) # Returns 2 (for 2D array)
print("Data type of elements:", arr.dtype) # Data type of elements
print("Item size in bytes:", arr.itemsize) # Size of each element in bytes
print("Total memory consumed:", arr.nbytes, "bytes") # Total memory usage

Key Takeaways:

  • .shape tells the (rows, columns) of an array
  • .size gives the total number of elements
  • .dtype shows the data type of elements
  • .ndim returns the number of dimensions

Array Indexing and Slicing

Just like Python lists, NumPy arrays support indexing and slicing.

1. Accessing Elements in a 1D Array

arr_1d = np.array([10, 20, 30, 40, 50])
print("First Element:", arr_1d[0])
# Access first element
print("Last Element:", arr_1d[-1])
# Access last element
print("Elements from index 1 to 3:", arr_1d[1:4]) # Slicing
print("Every second element:", arr_1d[::2]) # Step slicing

2. Accessing Elements in a 2D Array

arr_2d = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
print("Element at row 1, column 2:", arr_2d[1, 2]) # Accessing element
print("First row:", arr_2d[0, :]) # Accessing entire row
print("First column:", arr_2d[:, 0]) # Accessing entire column

Django-tutorial.dev is dedicated to providing beginner-friendly tutorials on Django development. Examples are simplified to enhance readability and ease of learning. Tutorials, references, and examples are continuously reviewed to ensure accuracy, but we cannot guarantee complete correctness of all content. By using Django-tutorial.dev, you agree to have read and accepted our terms of use , cookie policy and privacy policy.

© 2025 Django-tutorial.dev .All Rights Reserved.
Django-tutorial.dev is styled using Bootstrap 5.
And W3.CSS.