What have you tried?
Hint: Create a new empty list inside the function, then iterate over the matrix and you'll get the rows. Then you can limit the rows and the colums. The rows, if you count them for example or use
itertools.islice
. The colums can be addressed with the square brackets
[:2]
.
The naive solution:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
# if matrix size is huge, then
# this method is inefficient
# but for small lists, do not care...
for row in matrix[:2]:
print(row[:2])
from itertools import islice
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
for row in islice(matrix, 0, 2):
print(row[:2]) # <- creates a new list from index 0 to index 2 (exclusive)
Output:
[1, 2]
[4, 5]
The rest is your task.
You should also use the
REPL
to manually select rows and colums.
>>> matrix[0]
[1, 2, 3]
>>> matrix[0][:2]
[1, 2]
Pro-Tip: Later, after you've learned about lists (sequences in general), you can use numpy to do this task in a single step and memory efficient.
import numpy as np
matrix = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
])
print(matrix[:2,:2])
Output:
[[1 2]
[4 5]]
As you can see, the syntax for index access is more advanced. You can do this for each axis.