CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

Python – Sequence Types – Slicing

So far we have discussed the Sequence Types; list, tuple, range, str, bytes, bytearray and memoryview in Python. We have discussed creation of these types and accessing data from them. We have used index operator to access the data from the Sequence Types.

By using index operator we can access ONLY one element at the given index. Does it possible to access multiple elements at a time? For example, getting the substring from a given string.

Python supported Slicing operation to allow to access multiple elements at a time from these Sequence types. We can use slice operation on all the sequence types.

How Slice will work?

We use index operator to get a single element from the sequence type at the given index. We use the same index operator for slicing; but giving the number of elements to access along with index value separated by colon “:”. For example, data[start:stop] ; which is the slice of data from the index start to stop.

We will take another example, where we have the string “Hello, World!” and to get the portion of it “Hello”; we use the statement like below:

>>> data = "Hello, World!"
>>> data[0:5]
'Hello'
>>>

Slicing operation also allows to access the elements with a step value from the given index “start” to “stop”. For example, data[start:stop:step] ; which is the slice of data from the index start to stop with the step value.

To fetch, alternate elements from the above string; we can write our slice operation like below:

>>> data[0:13:2]
'Hlo ol!'

Observe that, the index starts from 0 until the last index (13) and the step value is 2 to get the alternate elements.

Note that, in the slice operation the values start, stop and step values are optional. If you do not specify any value for these; Python will take the default values. For example, for “start” the default value is “0”, for “stop” the default value is (number of elements in sequence type -1) and the default value for “stop” is “1”.

Look at the below examples, to get more clarity on this:

>>> data[::]
'Hello, World!'
>>> data[:5]
'Hello'
>>> data[::2]
'Hlo ol!'
>>>

We discuss more on Python in our upcoming Articles.

/Shijit/

Python – Sequence Types – Slicing

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top