2 Dimensional Arrays
Creating 2D Arrays in Python
A 2 dimensional (2D) array is like a grid or table with rows and columns. In Python, 2D arrays can be created using lists of lists. Each inner list represents a row.
Example of creating a 2D array with 3 rows and 3 columns:
array_2d = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
This creates a 3x3 grid where you can store and organize data in rows and columns.
What is a 2D array commonly used for in programming?
Accessing Elements in 2D Arrays
To access elements in a 2D array, use two indices: the first for the row and the second for the column. Indexing starts at 0.
For example, to get the element in the 2nd row and 3rd column:
value = array_2d[1][2]
This retrieves the number 6 from the example array:
array_2d = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Remember, the first index selects the row, and the second selects the column within that row.
What does the first index represent when accessing an element in a 2D array?
Modifying Elements in 2D Arrays
To modify an element in a 2D array, you assign a new value to a specific position using its row and column indices.
For example, to change the element in the 1st row and 2nd column:
array_2d[0][1] = 10
This updates the value at that position.
Example:
array_2d = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
array_2d[0][1] = 10 # Changes 2 to 10
print(array_2d)
# Output:
# [[1, 10, 3],
# [4, 5, 6],
# [7, 8, 9]]
Modifying elements this way allows you to update data stored in the 2D array.
Iterating Through 2D Arrays
To process or examine all elements in a 2D array, you use loops to iterate through each row and each column within that row.
A common method is to use nested for loops: the outer loop goes through each row, and the inner loop goes through each element in that row.
array_2d = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in array_2d:
for element in row:
print(element, end=' ')
print()
This code prints each element in the 2D array in a grid format. Iterating like this helps you read, modify, or analyze all values systematically.
In a 2D array, what does the outer loop typically represent?
2 Dimensional Arrays in Python
- Creating 2D Arrays in Python
- Accessing Elements in 2D Arrays
- Modifying Elements in 2D Arrays
- Iterating Through 2D Arrays