Create a 2D Array
Think of a 2D array as a grid with rows and columns. You can use the row and column positions to assign data and access it later.
The following code will make a 5 by 10 grid:
Matrix = [[0 for x in range(5)] for y in range(10)]
The following code will make a 5 by 10 grid:
Matrix = [[0 for x in range(5)] for y in range(10)]
Add data to the Array
Use the x and y grid coordinates to assign data:
Matrix[0][0] = "hello"
Matrix[1][0] = "my"
Matrix[2][0] = "friend"
Matrix[0][0] = "hello"
Matrix[1][0] = "my"
Matrix[2][0] = "friend"
Accessing the Array
The following code will display the data stored in the first row and first column:
print Matrix[0][0] # prints "hello"
print Matrix[0][0] # prints "hello"
Create a 2D array with data.
Accessing a 2D array
The following code will print the entire values of the first array. Note only one index is passed to the array - 0 will be the first array.
The following code will print an individual element - in this case the forth value stored in the forth array..
This is how to iterate through each array and display all items in each array.
If you want to access each item in each array you will need a nested for loop: The following code will display each array item from the first item in the first array (0a) to the last item in the last array (3e). Each item will be displayed on a seperate line.