Nested lists can be used to initialize 2D arrays. Here's an example:
two_d_array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(two_d_array)
# Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
This creates a 3x3 array using nested lists.
List comprehensions offer a more concise way:
rows, cols = 3, 3
two_d_array = [[0 for j in range(cols)] for i in range(rows)]
print(two_d_array)
# Output: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
This initializes a 3x3 2D array with all zeros.
You can access elements by specifying their row and column
two_d_array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
element = two_d_array[1][2]
print(element)
# Output: 6
This accesses the element in the second row, third column.
Modifying a 2D array is similar to accessing it
two_d_array[1][2] = 10
print(two_d_array)
# Output: [[1, 2, 3], [4, 5, 10], [7, 8, 9]]
This code modifies the value in the second row, third column to 10.
&&!adsense!&&
## Efficient Iteration Through 2D Arrays
You can iterate through a 2D array efficiently using nested loops
```python
for row in two_d_array:
for element in row:
print(element, end=" ")
print()
# Output :
1 2 3
4 5 10
7 8 9
This code prints all elements row by row.
You can flatten a 2D array to a 1D array using a list comprehension
flat_array = [element for row in two_d_array for element in row]
print(flat_array)
# Output : [1, 2, 3, 4, 5, 10, 7, 8, 9]
You can convert a 1D array to a 2D array by specifying the number of columns
cols = 3
two_d_array = [flat_array[i:i+cols] for i in range(0, len(flat_array), cols)]
print(two_d_array)
#Output: [[1, 2, 3], [4, 5, 10], [7, 8, 9]]
With a detailed exploration of 2D arrays in Python, this guide empowers programmers to handle data structures with ease.
CloneCoding
Innovation Starts with a Single Line of Code!