Back

Creating an array using a list

Q1. Study the following code:

myArray=[[1,2,3],[4,5,6],[7,8,9]]
print(myArray)

for i in range(3):
    for j in range(3):
        print(myArray[i][j],end=' ')
    print('\n')

Q2. How many elements does the array myArray have?
Q3. What index position is the first element?
Q4. What index position is the last element?
Q5. When you run this code, can you predict exactly what will get printed out?
Q6. Run the code and see if your prediction from the last question was correct.
Q7. If an array has lists as elements (sublists), we can access any individual element in the sublist. E.g. to get back index position 0 in the second element (i.e. index position 1), we would use:

temp = myArray[1][0]
print (temp)

Similarly, we can write a new value to an element in a sublist, like this:

myArray[2][1]=888
print(myArray)

Print out index position 0 of element 2 in myArray.
Q8. Change element 2 of the first sublist to be 333. Print out myArray.
Q9. Write a program to print out a nicely present grid of the first 16 integers starting at 1 using a list that has 4 elements, each element being a sublist of 4 numbers. When you print out the grid, it should look like this:

1         2         3         4

5         6         7         8

9        10       11       12

13      14       15       16

Q10. Change the number 14 so that it is 77. Print out the grid again.