Python 2D array
1. What is a 2D Array?
A 2D array is a data structure with rows and columns that can be thought of as a table or a grid. It is like having a matrix or a grid. Each element in the 2D array must access two indices: one row index and one column index.
- Think of a 2D array as a matrix or a grid. For example:
1 2 3
4 5 6
7 8 9
- The first index points to the row, and the second index points to the column.
- Element at
row 0, column 0is1 - Element at
row 2, column 1is8 - Element at
row 1, column 2is6
- Element at
2. Creating a 2D Array in Python
In Python, a 2D array is typically created using a list of lists. Each inner list represents a row, and the elements within it are the columns.
Example:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
- Here,
matrix[0]gives the first row:[1, 2, 3]. matrix[1][2]returns the element in the second row, third column, which is6.
3. Accessing Elements in a 2D Array
You can access elements in a 2D array by specifying both the row and column indices.
- Syntax:
array[row_index][column_index]- Example:
matrix[1][2]will access the value in column three, row two (6in the above example).
- Example:
Example of accessing elements:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Access element in first row, second column
print(matrix[0][1]) # Output: 2
# Access element in second row, third column
print(matrix[1][2]) # Output: 6
# Access element in third row, first column
print(matrix[2][0]) # Output: 7
4. Iterating Over a 2D Array
When you are working with 2D arrays, you typically have to iterate through the rows and columns to access or modify elements. This is done using nested loops.
- The outer loop iterates over the rows.
- Inner Loop iterates all columns in all the rows.
Example of Iteration Over a 2D Array:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Iterate through each row
for row in matrix:
# Iterate through each element in the row
for element in row:
print(element, end=" ")
print() # Print a newline after each row
Output:
1 2 3
4 5 6
7 8 9
- The outer loop runs over each row.
- The inner loop prints each element in the current row.
5. Modifying Elements in a 2D Array
You can modify elements in a 2D array by accessing the specific row and column, and assigning a new value.
Example of Modifying Elements:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Modify element at row 0, column 1 (change 2 to 99)
matrix[0][1] = 99
# Modify element at row 2, column 2 (change 9 to 100)
matrix[2][2] = 100
# Print the modified matrix
for row in matrix:
print(row)
Output:
[1, 99, 3]
[4, 5, 6]
[7, 8, 100]
6. Using List Comprehensions with 2D Arrays
List comprehensions are a concise way to create or manipulate lists in Python. You can use them to generate 2D arrays.
Example of a 2D Array Using List Comprehension:
To create 3×3 identity matrix with 1 in diagonal places and 0 in others:
identity_matrix = [[1 if i == j else 0 for j in range(3)] for i in range(3)]
# Print the identity matrix
for row in identity_matrix:
print(row)
Output:
[1, 0, 0]
[0, 1, 0]
[0, 0, 1]
- Explanation: The inner list comprehension [1 if i == j else 0 for j in range(3)] generates each row, and the outer list comprehension repeats this for each row (i from 0 to 2).
7. Advantages of List Comprehensions
- More concise than using loops.
- Typically more efficient and readable.
- Great for generating 2D arrays or matrices from patterns.
8. Using NumPy for 2D Arrays
While standard Python lists can be used for 2D arrays, the NumPy library is designed to work with arrays efficiently, especially for numerical data. NumPy arrays have better performance and many powerful built-in functions.
To use NumPy, you must first install it:
pip install numpy
Example of Using NumPy to Create a 2D Array:
import numpy as np
# Create a 2D array with NumPy
matrix_np = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
# Accessing an element
print(matrix_np[1, 2]) # Outputs: 6
# Modifying an element
matrix_np[0, 0] = 10
print(matrix_np)
Output:
[[10 2 3]
[ 4 5 6]
[ 7 8 9]]
Why Use NumPy?
- Efficiency: NumPy arrays are quite efficient than using Python lists while doing numerical work, especially working with large-scale data.
- Functionality: NumPy provides a number of functions that enable you to perform mathematical and logical operations on arrays.
9. Common Operations with 2D Arrays
Matrix Addition:
import numpy as np
# Create two 2D arrays
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
# Add matrices
C = A + B
print(C)
Output:
[[ 6 8]
[10 12]]
Matrix Multiplication:
C = np.dot(A, B) # Matrix multiplication
print(C)
Output:
[[19 22]
[43 50]]
10. Reshaping 2D Arrays with NumPy
With NumPy, you can reshape a 1D array into a 2D array (or any shape you want).
arr = np.array([1, 2, 3, 4, 5, 6])
# Reshape to a 2x3 matrix
reshaped_arr = arr.reshape(2, 3)
print(reshaped_arr)
Output:
[[1 2 3]
[4 5 6]]
Summary of Key Points:
- 2D Array: A list of rows and columns (like a table or matrix).
- Creating 2D Array: A list of lists in Python.
- Accessing: Use two indices,
array[row][column]. - Iteration: Use nested loops to go through rows and columns.
- Modification: Directly assign new values using indices.
- List Comprehensions: Efficiently generate and manipulate 2D arrays.
- NumPy: A powerful library for handling large and complex 2D arrays, with better performance.