In Python, a multi-dimensional array (or list) is essentially a list of lists (or a list of lists of lists, etc.). These are useful for representing more complex data structures, like matrices or grids.
For example, a 2D array (like a table) can be created as a list of lists. Here’s a quick guide:
Creating a 2D Array
# A 2D array (list of lists)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Accessing elements
print(matrix[0][0]) # Output: 1 (first row, first column)
print(matrix[1][2]) # Output: 6 (second row, third column)
# Updating an element
matrix[1][1] = 10
print(matrix) # Output: [[1, 2, 3], [4, 10, 6], [7, 8, 9]]
Looping through a 2D Array
for row in matrix:
for element in row:
print(element, end=" ")
print() # Newline after each row
Creating a 3D Array
For a 3D array (e.g., a cube), you would nest lists further:
# A 3D array (list of lists of lists)
cube = [
[
[1, 2],
[3, 4]
],
[
[5, 6],
[7, 8]
]
]
# Accessing elements
print(cube[0][1][1]) # Output: 4 (first block, second row, second column)
Using Numpy for Multi-Dimensional Arrays
The numpy
library provides more efficient and convenient multi-dimensional arrays, called ndarrays.
import numpy as np
# Creating a 2D array with numpy
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Accessing elements
print(matrix[0, 0]) # Output: 1
print(matrix[1, 2]) # Output: 6
numpy
arrays allow for more advanced operations and optimizations, especially for mathematical and scientific computing tasks.
Comments
Post a Comment