Dipping my toes into multi dimensional array slicing in Python and am hitting a wall of confusion with the following code
# Example 2D array
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Basic slicing
result = matrix[0:2][1:2]
print(result)
So when I read this example with the following line: result = matrix[0:2][1:2]
I read this as result = matrix [rows][columns]
So to me I would think that this should return the first two rows of the matrix, and then the specified columns as per the slice [1:2]
So I would imagine it should return first the rows first -> [1, 2, 3], [4, 5, 6]
Then after this it should take another slice with [1:2] so I would guess it should return [5]? Row 1 and up to the 2nd element?
When I run the code the following is the result
[[4,5,6]]
I am totally wrong so was wondering what am I missing?
I tried to google this kind of syntax where it has matrix[X:X][X:X] but I was not able to find out what is this called so if anyone can shed some light or point me in the right direction I would greatly appreciate it!
When get matrix[0:2]
you receive 2 first elements of basic matrix with index 0 and 1:
[1, 2, 3], [4, 5, 6]
. Then you try slice[1:2]
in getted before result you receive only 1 element with index 1 which equal [4, 5, 6]