As discussed in my previous article, slicing is extracting element/elements from the iterable based on the index/indices value. This article focuses more on different examples of slicing. Python follows the below syntax for slicing.
variable_name[start index : end index : step/jump]
Default value of start index is '0' and default value of step/jump is '1'. 'Step/Jump' is an optional argument that determines the increment between each index for slicing. With the above syntax in mind, let's practice slicing.
Suppose 'var' is a variable storing string value "Coding is fun".
var = 'Coding is fun'
C o d i n g i s f u n
0 1 2 3 4 5 6 7 8 9 10 11 12
-13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
var[0:4] will yield output as 'Codi'
In the above case index value from '0' to '3' are extracted and element with index value '4' is excluded. The jump value is the default value i.e. '1'. Below are some basic examples of slicing.
var[0:5:2] will yield 'Cdn
Here, every 2nd term is picked
var[::] will yield 'Coding is fun
Since no value is mentioned, therefore default values are used
var[4::] will yield 'g is fun
Now there is one more concept in slicing called jump direction. Default value of jump is '1' which indicates that direction to follow for slicing is from left to right. In case, if we mention jump value as '-1', the direction will reverse from right to left. By mentioning values of start index and end index, we provide direction for Python to slice the element. This direction(called moving direction) should be inline with the jump direction. For reference to direction, kindly follow the above table made to highlight the indexing of each element. Let's understand the concept with the below example.
C o d i n g i s f u n
0 1 2 3 4 5 6 7 8 9 10 11 12
-13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
var[0:13:1] will yield 'Coding is fun
Here the direction indicated by index values(moving direction) and direction of
jump is same i.e. left to right.
var[-1:-13:-1] will yield 'nuf si gnidoC
Here the direction indicated by index values(moving direction) and direction of
jump is same i.e. right to left.
Similarly,
var[8:0:-1] will yield ' si gnido
Here, the moving direction and direction of jump is same i.e. right to left.
Now, if the moving direction and jump direction is not same, no result will occur as it will confuse Python for the output.
C o d i n g i s f u n
0 1 2 3 4 5 6 7 8 9 10 11 12
-13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
var[-1:-9:1] will yield no result
Similarly
var[-1:-9:] will yield no result, as default value of jump is '+1'
Same is the case below
var[5:0] will yield no result, as jump direction is '+ve' and moving direction
is '-ve-
Hope, the above examples of slicing are sufficient to completely understand the concept of slicing. Drop your thoughts in the comment section!