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.

Programs
01234567
-8-7-6-5-4-3-2-1

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]Code language: Python (python)
>>> str[0] # first character in the string
'P'
>>> lst[0] # first item in the list
2
>>> str[-1] # last character in the string
's'
>>> lst[-1] # last item in the list
10
>>> str[1] # second character in the string
'r'
>>> lst[1] # second item in the list
4
>>> str[-2] # second last character in the string
'm'
>>> lst[-2] # second last item in the list
8Code language: Python (python)

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]
'og'
>>> str[-6:-4]
'og'
>>> lst[2:4]
[6, 8]
>>> lst[-3:-1]
[6, 8]
Code language: Python (python)

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]
'ga'
>>> str[-5:-2:2]
'ga'
>>> lst[1:6:2] 
[4, 8]
>>> lst[-4:-1:2] 
[4, 8]Code language: Python (python)

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]
'mar'
>>> str[-2:-5:-1]
'mar'
>>> lst[3:1:-1] 
[8, 6]
>>> lst[-2:-4:-1] 
[8, 6]Code language: Python (python)

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]
'Pro'
>>> str[3:]
'grams'
>>> lst[:3] 
[2, 4, 6]
>>> lst[3:] 
[8, 10]Code language: Python (python)

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]
'smargorP'
>>> lst[::-1]
[10, 8, 6, 4, 2]Code language: Python (python)
Content Protection by DMCA.com

Download HitXP Mobile App

Get it on Google Play
Gurudevhttps://www.hitxp.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.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

FacebookLike
InstagramFollow
PinterestFollow
RSS FeedSubscribe
Sound CloudFollow
TwitterFollow
YoutubeSubscribe

Latest Articles

The Power of Democracy: How Free Societies Foster Innovation in Science and Technology

Democracy allows freedom of speech and thought, boosting creativity and innovation. This leads to scientific breakthroughs and technological advancements.

How does GOD helps us?

Do prayers really help? Do miracles happen when we are in trouble? Does God really help us in times of need? Are prayers enough to save us during bad times? How should we face problems?

Sanskrit poem on Ramayana – read in reverse becomes Mahabharata!

A Sanskrit poem about Ramayana when read in reverse direction becomes a poem on Mahabharata!

The difference between Itihasa and Puranas

Documentation of ancient Indian history and the historical events of Indian civilization in the form of Itihasa and Puranas - Ramayana and Mahabharata.

Latest Music Notations

Jai Shri Ram – Adipurush – Piano Notations

Piano, Keyboard, Violin, Flute notes, Guitar Tabs and Sheet Music of the Song Jai Shri Ram from the 2023 Hindi movie Adipurush in Western and Indian Notations.

Sojugada Soojumallige – Garuda Gamana Vrishabha Vahana – Piano Notations

Piano, Keyboard, Violin, Flute notes, Guitar Tabs and Sheet Music of the Song Sojugada Soojumallige from the 2021 Kannada movie Garuda Gamana Vrishabha Vahana in Western and Indian Notations.

Oo Antava Mava – Pushpa – Piano Notations

Piano, Keyboard, Violin, Flute notes, Guitar Tabs and Sheet Music of the Song Oo Antava Mava from the 2022 Telugu movie Pushpa in Western and Indian Notations.

Kaa Chalige Bangalore (Tiningaa Miningaa Tishaaaa) – Salaga – Piano Notations

Piano, Keyboard, Violin, Flute notes, Guitar Tabs and Sheet Music of the Song Tiningaa Miningaa Tishaaaa (Kaa Chali Ge) from the 2022 Kannada movie Salaga in Western and Indian Notations.
Content Protection by DMCA.com