SDD Topic has been refreshed!
An array is a data structure used to hold multiple values. Each element has a unique index (or subscript). And the the number of elements can be accessed by using the length predefined function (Python).
A 1D array is where you specified the number elements (columns) in an array – it has one dimension.
When declaring a 2 dimensional (2D) array we specify the rows and columns
Python treats this as a list within a list. You will notice that we have initialised each element in the array with a value of 0.
This would create a 2D array called my2dArray with 3 rows and 8 columns. If we look closer at the declaration below.
You will see that just like 1D arrays, the first index for each row and column is from 0.
This would create a 2D array with 3 rows and 8 columns like below:
In Python we could visualise the 2D array as below:
In order to traverse through a 2D array - we will usually need to use a nested loop structure. One loop (the outer loop) will iterate through each row of the array and then the nested loop will traverse through each column of that row.
For example the code below would iterate through a 2D array and place a random integer between 1 and 10 in each element. This code assumes that the array has already been created as in the earlier example.
If we print the 2d array (in Python) using the following code
We would get the following output
[[7, 4, 4, 5, 6, 7, 9, 6], [9, 8, 2, 3, 8, 1, 7, 7], [4, 6, 2, 6, 5, 2, 5, 8]]
But if we want to display it row by row we will need to process the output. We will display it row by row, whilst removing the square brackets and commas.
This would produce output shown below:
6,1,6,9,7,7,6,1
2,1,8,2,6,5,1,7
5,3,6,8,7,6,1,6
You will notice that we have delimited the 2d array using a comma.
This would be useful if the array was to be written to a file.
As you may have used at higher the len() function can be used to return the amount of elements in an array. However we have to consider that the 2D array has two dimenssions - the number of rows and the number of columns.
We could use the len function to find the number of rows and columns.
As Python stores a 2D array as a list of lists len(my2dArray) returns the amount of rows and len(my2dArray[i]) returns the number of columns (in that row).
If we have the contents of a file - such as the one below:
0,0,30,2,21,13,23
29,3,29,30,7,8,25
Then if we are to read the file into a 2D array then we need to process the file one line at a time. Reading the first row of the file into the first row of the 2D Array. The code for this is very similar to that which we used at Higher but we will add the suitable code to deal with the fact that we are dealing with an array with 2 dimensions.
The code below would read from the file and populate the array one row at a time.
An explanation of this code is below