When we are working with lists or strings, very often we feel the need to slice, cut, or iterate through intervals. I used to feel very uncertain until I discovered this slicing trick.

In this blog, we will understand slicing with a wide variety of examples on strings, lists, and tuples.

▶ Before we move to the slicing technique let’s see some basics of indexing.

>>> str  = "AaBbCcDdEe"

>>> str[2] ## return value at 1st index from front
'B'
>>> str[-2] ## return value at 1st index from back
'E'

Decode slicing

In the above example, we saw that when we are selecting only one element from the string we simply put the index. In the case of slicing, we need an interval. And to indicate an interval we use [<from>:<to>] in Python.

Here I will be using strings in the examples. But the technique works exactly the same with tuples and lists. You can try this on your own considering it as a practice lesson.

All the examples are done in Python interpreter.

>>> str  = "AaBbCcDdEe"

>>> str[0:len(str)] ## [start_index=0 : end_index=len(str)]
'AaBbCcDdEe'

#python3 #coding #python #programming #data-structures

Slicing in Python
4.40 GEEK