Understand the slice notation

Explanation

Here we will understand the slice notation 

It is easy to learn like :

a[start:stop]  # items start through stop-1
a[start:]      # items start through the rest of the array
a[:stop]       # items from the beginning through stop-1
a[:]           # a copy of the whole array

There is also the step value, Which we can use with any of the above:

a[start:stop:step] # start through not past stop, by step

Here we have to note that the :stop value is used to represent the first value. And that is not in the selected slice. So, we have the difference between stop and start and that is the number of elements selected. (if step is 1, the default).

The other feature is that start or stop maybe a negative number. that means it will start counting from the end of the array instead of the beginning. So:

a[-1]    # last item in the array
a[-2:]   # last two items in the array
a[:-2]   # everything except the last two items

Similarly, step maybe a negative number:

a[::-1]    # all items in the array, reversed
a[1::-1]   # the first two items, reversed
a[:-3:-1]  # the last two items, reversed
a[-3::-1]  # everything except the last two items, reversed

Here will take an example, like one ask for a[:-2] and a only contains one element. So at that time, one will get an empty list instead of an error. And sometimes there will be an error.  So you have to be aware that this may happen.

Relation to slice() object

The slicing operator [] is actually being used in the above code with a slice() object using the : notation (which is only valid within []), i.e.:

a[start:stop:step]

is equivalent to:

a[slice(start, stop, step)]

 

Also read, In noncat table, change the category for item UF39 to null

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *