Home Code Slicing in Python to extract sub strings or sub lists in either...

Slicing in Python to extract sub strings or sub lists in either direction

Slicing is a very powerful feature of the Python programming language. As the name suggests, it allows you to quickly extract small slices of data from python data structures like lists and strings. It is also very easy to use slicing to reverse an entire string or list in Python with a simple notation.

The difference between slicing and indexing is that indexing allows you to extract data at a given single position, while slicing allows you to extract data over an entire range. So while indexing can be used to get a single char from a string, slicing can be used to extract a substring from a string.

Indexing in Python – positive and negative indices

To understand slicing, first we need to understand how indexing is allowed in Python in both the directions. See below table to get a clear overview of what this means.


In the above table, the string “Programs” is show along with indices of each of its chars. Note that in the reverse indexing notation, one can start counting the index from the back or from the end. And reverse indexing starts with -1.

So a given item in a Python string or list has two indices, a zero based positive index that is counted from left to right, or from front to back, and a negative index that is counted in the reverse direction. The negative index can be used to access the last item and is very useful because you can access the last item without having to calculate the length. See below example

str = "Programs"

lst = [2,4,6,8,10]
>>> str[0] # first character in the string

>>> lst[0] # first item in the list

>>> str[-1] # last character in the string

>>> lst[-1] # last item in the list

>>> str[1] # second character in the string

>>> lst[1] # second item in the list

>>> str[-2] # second last character in the string

>>> lst[-2] # second last item in the list

Slicing in Python – can use positive or negative indices to slice

Now that we have understood both positive and negative indexing in Python, let us proceed to slicing. In strings, slicing is used to extract substrings. In lists, slicing is used to extract sub lists. The syntax of using slicing is [start_index:end_index+1:stride].

The default stride is 1. When the stride value is positive slicing moves forward i.e. from left to right. If the stride value is negative, slicing moves backwards i.e right to left. When the absolute striding value is 1 (i.e. 1 or -1) all adjacent values will be considered. If the absolute striding value is more than 1 (like 2, -2, -3, 3, etc) then that many adjacent values will be skipped. Let us see few examples.

>>> str[2:4]

>>> str[-6:-4]

>>> lst[2:4]
[6, 8]

>>> lst[-3:-1]
[6, 8]

In the below example, we are incrementing the stride by 2. So after taking the value at start index, it will skip two indices every time. So, after taking ‘g’ at index 3, it will move to ‘a’ at index 5, the next index is again 7 which is beyond end index (6), so slicing stops there. Note that, again here we can use the negative indices i.e. indices counted backwards to get the same result.

>>> str[3:6:2]

>>> str[-5:-2:2]

>>> lst[1:6:2] 
[4, 8]

>>> lst[-4:-1:2] 
[4, 8]

When the stride is negative, slicing is done in the reverse direction, similar to how str[-1] points to the last char of the string. So we should specify the start and end index in reverse direction as well. Note that the indices can be either positive indices or negative indices. See example below.

>>> str[6:3:-1]

>>> str[-2:-5:-1]

>>> lst[3:1:-1] 
[8, 6]

>>> lst[-2:-4:-1] 
[8, 6]

The default start index and end index are the first indices or last indices depending on the direction specified by the stride. See examples below.

>>> str[:3]

>>> str[3:]

>>> lst[:3] 
[2, 4, 6]

>>> lst[3:] 
[8, 10]

Using Python slicing to reverse a string or a list

Slicing can be used to reverse a string or a list with ease using its simple notation. Just use the negative stride of -1 and leave everything else to the default values. That is it!

>>> str[::-1]

>>> lst[::-1]
[10, 8, 6, 4, 2]
Content Protection by DMCA.com
Gurudev is the developer of Gurunudi AI Platform. This is his official website where he pens his thoughts on a wide range of topics, answers queries, shares resources and tools developed by him.


Please enter your comment!
Please enter your name here


Subscribe to HitXP Articles

To be updated with all the latest articles, offers and special announcements.

Latest Articles

An Efficient Strategy to fight Corona Virus

By setting up local police station level online delivery networks for essential items like grocery, medicines - the need for general public to come out of their homes can be removed.

Rising pollution can cause Pandemics deadlier than Corona Virus

Rising pollution can expose ancient killer microbes that may cause pandemics more deadlier than Corona. Melting Ice Sheets can resurrect killer agents of the past.

Corona Virus, SARS – Why are new viruses increasingly originating from China?

The reason why new strains of deadly viruses are emerging from China. Viruses like coronavirus and SARS should be stopped from evolving and spreading to prevent another global pandemic.

Evolution of life – primitive cells, complex organisms, intelligence, what next after humans?

Evolution of life from primitive life forms to complex multi cellular organisms to intelligent human species - the advent of AI raises a natural question - What next after human?
Content Protection by DMCA.com