Python - List Slicing

Today I am going to explain the concept that I was confused with at the beginning(While learning python). Well, the topic is list slicing.To me, this notation needs a bit of picking up. It looks extremely powerful, but I haven't quite got my head round it and am looking for a good guide.This post will be a simple short explaination of this concept.
Generally, List slicing can be easily understood except for negative index accessing.So, let me explain this concept by naming the indices as start and end and the skipping number as step.My explaination will be similar to the implementation of range method in python.


            a[start:end] # items start through end-1
            a[start:]    # items start through the rest of the array
            a[:end]      # items from the beginning through end-1
            a[:]         # a copy of the whole array
           
There is also the step value, which can be used with any of the above:

            a[start:end:step] # start through not past end, by step
           
The key point to remember is that the :end value represents the first value that is not in the selected slice. So, the difference beween end and start is the number of elements selected (if step is 1, the default). The other feature is that start or end may be a negative number, which means it counts 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
           
Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for a[:-2] and a only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, so you have to be aware that this may happen.

Leave a comment