All you need to know about List Slicing in Python

Jigyasa
3 min readJun 10, 2021

Most versatile compound data type in Python is List. Lists may contain items of different types or same type. Lists can be indexed and sliced. All slice operations return a new list containing the requested elements.

I am creating a list of numbers:

List indexing starts from 0. For list of length n . Indexing will range from 0 to n-1.

We can retrieve any element in list by referring to its index.

At index/position/address/location 3, we have element 4. So output is 4.

We can return multiple elements of list too. Syntax of this slicing will be listName[startingIndex:endingIndex], this will return elements from startingIndex to endingIndex (will exclude element at endingIndex).

Not providing startingIndex take 0 as starting position by default. Similarly by default n will be taken as endingIndex. If both were absent then entire list will be returned without slicing.

What if the index provided is not available at all? It will throw IndexError:list index out of range

So far slicing is done in sequence order of elements. What if we want to retrieve alternative elements in list. This can be done using slicing. Syntax is list[startIndex:endingIndex:Step].

Here step size is 2, so it jumped to next to next index .
This will return elements at 0,4,8,12,16…etc (Depends on list size, in this example list is of size 7. So 0,4 location elements will be in output)

So far the retrieval is from left to right positioning of list which is convention retrieval. Beauty of python slicing is it can print list in reverse. Can slice elements in reverse order(right to left) too.

[1,2,3,4,5,6,7]Indexing from right to left is
[-n,-n+1,...,-1]
In this example its going to be
[-7,-6,-5,-4,-3,-2,-1]

Now the reverse retrieval of entire list using slicing concept with step number in syntax.

To avoid confusion if step number is negative its from right to left. In the absence of step number or its positive then it will be left to right which is traditional retrieval.

--

--