0

Can somebody please explain the output of this code?

a= np.array([[1,1,1], [1,0,0], [1,0,0]]) print (a[1:3, 1:3])

21st Jun 2019, 6:26 PM
Shihab
5 Réponses
+ 2
Shihab Uddin because you said print(a[1:3, [1:3]), which tells python: slice an array called "a" start with 1 and stop before 3, when you finish go to each element you have sliced and also start with 1 and stop before 3. So this code slices an already sliced slice. The first [1:3] gets these two elements: [1,0,0] and [1,0,0]. Then the second [1:3] that you have wrote slices each one of the previous slices (starting from index 1 and ending before 3) resulting in these: [0:0] [0:0]
21st Jun 2019, 7:03 PM
Mo Hani
Mo Hani - avatar
+ 1
After you had imported numpy module as np, you made an array "a" of three elements [1,1,1] [1,0,0] [1,0,0] You then sliced the array by this way [x:y:z] where the factor "x" represents the starting point where your slice will begin, "y" represents the ending point where your slice will stop before it, and "z" represents the step taken from "x" to "y". You have wrote print(a[1:3]), so you told python: slice the array called "a" start from element number 1 and stop before element number 3 and take the default step which 1 and then print the result. (Which results in printing last two elements in the array] And since python starts counting from 0, element number 1 to python is considered the second element we see by our eyes. Let me know if somethig isn't clear.
21st Jun 2019, 6:45 PM
Mo Hani
Mo Hani - avatar
+ 1
Mo Hani got it! Thanks a lot.
21st Jun 2019, 7:04 PM
Shihab
0
You forgot this line that can actually give you a clue: import numpy as np This is a multidimensional numpy array slicing. The two dimensions are row and column, the slicing syntax [1:3, 1:3] means row index 1 and 2 (less than 3) and column index 1and 2.
21st Jun 2019, 6:44 PM
Tibor Santa
Tibor Santa - avatar
0
But how the output could be [[0,0] [0,0]] ?
21st Jun 2019, 6:56 PM
Shihab