• Srujan kachhwaha

Slicing In Python, Slice Your Way Out Inside Lists And String.

Updated: Jul 25, 2021

So far we have seen, the dynamic nature of python, its built-in functions, that help us find our solutions with a single function call.

In this post, We will look at the very important and yet easy concept that will help us traverse lists and strings with a finger snap! Slicing, This single concept will become your one-stop call for all list and string problems.

Sequence In Python

Python uses the term 'sequence' for the data structure that is in a linear fashion. For example, take strings, they are a sequence of characters. List on the other hand is a sequence of items or objects inside them!

Remember this concept, You can apply Slicing to all those data structures that python defines as a sequence.

Slicing In Python Using Strings

Let's take a string.

>>> s = 'welcome to soulcodes.org'

Now, suppose I told you to give me alternate characters from this string. For example, alternate characters in the above string will be :

"wloet oloe.r"

Python gives us a one-line solution to this problem! No loops, we will find our way out using slicing.

>>> s[0::2]
'wloet oloe.r'

Let's understand the syntax of slicing, Slicing says that :

s[start-index : end-index: step]

I hope you understand what the start-index and end-index are, The step is, by how much value you want to jump.

In our example, We give:

Start-index 0

End-index We did not specify the end index because we want to go till the end!

Step 2

An important thing to note is, The End-index value is exclusive, This means if you want to go to the index value of 5, You should give the End-index value as 6.

>>> s = "Slicing with Python Is Easy"
>>> s[0:7]

Now that you know how slicing works, it's up to you how you use that concept in innovative and creative ways.

Let me give you one more way you can use this:

>>> "I am Learning Python"[5::]
'Learning Python'

Reverse A String In Python Using Slicing

So, how you will reverse a string using the concept of slicing? Think a bit! Can't we start from the last index and go to the 0th index?

Let's try this out

>>> s = "I am learning Python"
>>> s[-1::-1]
'nohtyP gninraeL ma I'

Yeah! sequences in python can work with negative indexes!

start-index -1 ( To Acces The Last Element Of The String )

End-index didn't specify cause we want to travel till the end

Step -1

So, we start from -1 then -2 then -3 then -4 up to -20!

Python, Slicing In Lists

We can use slicing to all those data structures that are a sequence. Lucky for us, the List is also a sequence.

>>> l = [1,2,3.5,'hello']
>>> l[1::]

You can apply all the above slicing techniques we discussed in strings to the Lists. Why don't you try and exercise what we learned in strings and apply them in lists? They both are the same.

Comment down if you got any errors, we will solve them together. For now, let's wind up this post here. See you people in the next post.

17 views1 comment