My question may look too simple, but I am curious to know why this is available in Python.
Assume we have defined an array of size of (4,3):
import numpy as np
a=np.random.randint(15,size=(4,3))
The result would be something like below:
array([[ 7, 6, 1],
[ 5, 3, 6],
[12, 10, 11],
[ 1, 3, 4]])
What is difference between:
a[0]
Result:
array([7, 6, 1])
and
a[0:1]
Result:
array([[7, 6, 1]])
As both of them return the same part of the matrix:
7, 6, 1
I do know that the difference is the shape as the former one is (3,) and the later one is sized of (1,3). But my question is that why we need to have these kinds of shapes. If you are familiar with Matlab, giving a range using colon gives you two rows, but in Python, it returns the same information with different shape. What is the point? what is the advantage?
The reason is that you can be confident that array[x:y] always returns a subarray of the original array. So that you can use all the array methods on it. Say you have
map(lambda1, array[x:y])
Even if y-x == 1 or y-x == 0, you are guaranteed to have a array returned from array[x:y] and you can do map over it. Imagine if array[1:2] instead returned a single item i.e. array[1]. Then the behavior of the above code depends on what array[1] is, and it is probably not what you want.
I will try to explain with a simplified example.
simple_matrix = [[0,1,2],[3,4,5],[6,7,8]]
The following code is printing a single element from this list of lists:
print (simple_matrix[0])
The element printed is a list, this is because the element at index 0 of simple_matrix is only a list:
>>> [0,1,2]
The use of slicing, like in the following example, returns not a single element but two. In this case it is simpler to expect a list of elements as return and that is exactly what we see as result:
print (simple_matrix[0:2])
>>> [[0, 1, 2], [3, 4, 5]]
What seems to puzzle you is this output:
print simple_matrix[0:1]
>>> [[0, 1, 2]]
You get this output because in this case your are not getting a single element from the list like we did in the 1st example but because you are slicing a list of lists.
This slice returns a list containing the sliced elements, in this case only the list [0, 1, 2].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With