Difference between [] and [[]] in numpy
Can anyone ask what is the difference between (if a is some numppy object, say: array) a [1] and [[1]]. If I understand correctly, I can edit one element a with [[1]] but not with [1] ... any other difference? Is it also something like this with [] I just loop through some elements and with [[]] create a copy? If it matters, I am using python 3.
source to share
When you say a[1]
you get the item at the index 1
(second) from a
. a[[1]]
, on the other hand, is not a special syntax, it simply means "get the items a
indicated by the indices in the list [1]
". You can also say a[[1, 2]]
or use another array as an index. The practical difference is that it a[1]
will be the only scalar element and a[[1]]
will be an array with size 1 (assuming it a
is one size).
As regards the appointment, you will find both a[1] = 2
, and a[[1]] = 2
work equally well. This is due to the NumPy semantics translation , which makes it easy to compare objects of different dimensions. However, the actual sizes a[1]
and are a[[1]]
different, and this matters depending on the context.
Read more about indexing in NumPy here .
source to share