Understanding Multiple Dimensions in Python Arrays
Interact with the 3D visualization to explore array dimensions
Loading 3D visualization...
Understanding Dimensions in Python Arrays
What are Dimensions in Python Arrays?
Let's dive deep into the concept of dimensions
In Python, the dimensions of an array refer to the number of indices needed to select an individual element. Each dimension represents a level of nesting in the array structure.
- 1D Array (Vector): A single row or column of elements. Example: [1, 2, 3, 4]
- 2D Array (Matrix): A table of rows and columns. Example: [[1, 2], [3, 4]]
- 3D Array (Cube): A cube of elements. Example: [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
- N-D Array: Arrays with more than three dimensions, often used in complex scientific computations.
The number of dimensions is also referred to as the "rank" of the array. Understanding dimensions is crucial for data manipulation, especially in fields like data science and machine learning.
Visualizing Dimensions
Let's see how different dimensions look
[1, 2, 3, 4, 5]
A 1D array is like a single row or column of elements.
Accessing Elements in Multi-Dimensional Arrays
How to select elements based on dimensions
# 1D Array
array_1d = [1, 2, 3, 4, 5]
print(array_1d[2]) # Output: 3
# 2D Array
array_2d = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(array_2d[1][2]) # Output: 6
# 3D Array
array_3d = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
print(array_3d[1][0][1]) # Output: 6
As the number of dimensions increases, we need to use more indices to access specific elements. Each set of square brackets corresponds to a dimension.
Quiz: Test Your Understanding
Answer these questions about array dimensions
Code Completion Exercise
Complete the code to create and manipulate a 3D array
import numpy as np
# Create a 3x3x3 array of zeros
array_3d = np.zeros((3, 3, 3))
# Fill the array with values
for i in range(3):
for j in range(3):
for k in range(3):
array_3d[i][j][k] = i + j + k
# TODO: Write code to print the sum of all elements in the array
# Hint: Use np.sum()
print("Sum of all elements:", )