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

%MINIFYHTML8004e33129b1248be68bc8ff09ed7bbe42%
str = "Programs" lst = [2,4,6,8,10]
>>> 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 8

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]

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]

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]

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]

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]

Download HitXP Mobile App on Google Play

Get it on Google Play
Content Protection by DMCA.com
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 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.

Online Education should be interactive and innovative – Fun to Learn

For online education to succeed for smaller classses - it should be as interesting as cartoons. Online education cant succeed unless it is more interesting, interactive and innovative than offline schooling.

The Complete List of Dhatus – Sanskrit Root Words and their English meaning

A complete list of all dhatus (root words or verb roots) in Sanskrit dictionary and their meanings with corresponding IPA transliteration.

Sanskrit Lesson 4 – Word Creation Magic using Dhatus

Learn how easy it is to create new words in Sanskrit using root words called Dhatus. This simple process of Sanskrit grammar powers the entire language.

Latest Music Notations

So Gaya Ye Jahan – Tezaab – Piano Notations

Piano, Keyboard, Violin, Flute notes, Guitar Tabs and Sheet Music of the Song So Gaya Ye Jahan from the 1988 Hindi movie Tezaab in Western and Indian Notations.

Background Theme (BGM) – Mouna Ragam – Piano Notations

Piano, Keyboard, Violin, Flute notes, Guitar Tabs and Sheet Music of the Song Background Theme (BGM) from the 1986 Tamil movie Mouna Ragam in Western and Indian Notations.

Dil Kya Kare Jab Kisi Se – Julie – Piano Notations

Piano, Keyboard, Violin, Flute notes, Guitar Tabs and Sheet Music of the Song Dil Kya Kare Jab Kisi Se from the 1975 Hindi movie Julie in Western and Indian Notations.

Albela Sajan Aayo Re – Hum Dil De Chuke Sanam – Piano Notations

Piano, Keyboard, Violin, Flute notes, Guitar Tabs and Sheet Music of the Song Albela Sajan Aayo Re from the 1999 Hindi movie Hum Dil De Chuke Sanam in Western and Indian Notations.

Download HitXP Mobile App on Google Play

Get it on Google Play
Content Protection by DMCA.com