The slice notation is a very powerful concept in Python. It allows us to extract parts of a sequence (such as a list or string) effortlessly.
The notation takes three values.
Suppose we have a string called myString
.
The notation myString[a:b:c]
indicates that we want to extract a slice from myString
that starts from index a
, up to (but not including) index b
.
a
and b
are both optional. If a
is omitted, the slice starts from the first element. If b
is omitted, the slice ends at the last element.
Finally, we have c
. This is the stepper; it allows us to skip elements. For instance, if the stepper is 2, we’ll get every 2nd element in the string.
If c
is positive, the slice steps from left to right. If it is negative, it steps from right to left.
c
is also optional. If omitted, the default value is 1.
Confusing? Let’s look at some examples.
Examples:
Suppose
myString = 'abcdefg'
myString[1:5:1]
gives us elements from index 1 up to (but not including) index 5. In other words, it gives us elements from index 1 to 4. Hence, we get the string 'bcde'
.
myString[:5:1]
gives us elements from the start (as a
is omitted) of the string to index 4. Hence, we get the string 'abcde'
.
myString[1::1]
gives us elements from index 1 to the end of the string (as b
is omitted). Hence, we get the string 'bcdefg'
.
myString[::1]
gives us 'abcdefg'
. In other words, as the stepper is 1, we simply get every element in the string.
On the other hand, myString[::3]
gives us 'adg'
(i.e. every 3rd character in the string) as the stepper is 3.
myString[::-1]
gives us 'gfedcba'
as the stepper is negative one (i.e. every character in the string starting from the right)
myString[::-2]
gives us 'geca'
(i.e. every 2nd character in the string starting from the right)
myString[-1:-5:-2]
gives us 'ge'
. This is the hardest to understand if you are not familiar with using negative indices for lists.
Recall that we can use negative indices when accessing the elements in a list? Negative indices start from the back of the list.
Index -1 refers to the last element, -2 refers to the second last and so on. In other words, myString[-1]
gives us 'g'
while myString[-2]
gives us 'f'
.
myString[-1:-5:-2]
means we want to extract elements from index -1 ('g'
), up to but not including index -5 ('c'
). In other words, the elements are extracted from 'f'
to 'd'
. As the stepper is -2, we get every second element (from right to left). Hence, the result is 'ge'
.