Understanding Slicing in Python

Slicing is one of the most useful tools in the Python language.

As such, it is important to have a good grasp of how it works.

Basic Notation

Let’s say we have an array called ‘list’.

list[start:stop:step]
  • start: where you want the slicing to begin
  • stop: until where you want the slicing to go, but remember the value of stop is not included
  • step: if you want to skip an item, the default being 1, so you go through all items in the array

Indices

When slicing, The indices are points in between the characters, not on the characters.

For the word ‘movie’:

 +---+---+---+---+---+
 | m | o | v | i | e |
 +---+---+---+---+---+
 0   1   2   3   4   5 
-5  -4  -3  -2  -1  

If slice from 0 until 2, I get ‘mo’ in the example above and not ‘mov’.

Since a string is just a list of characters, the same applies with to list:

my_list = [1, 2 , 3, 4, 5]

Becomes:

 +---+---+---+---+---+
 | 1 | 2 | 3 | 4 | 5 |
 +---+---+---+---+---+
 0   1   2   3   4   5 
-5  -4  -3  -2  -1  

Examples

We have a variable containing the string ‘movie’ like so:

word = 'movie'

All the examples below will be applied to this word.

Example 1

To get the first two characters:

sliced = word[:2]
print(sliced)
mo

Notice that we could have used 0 to denote the beginning, but that is not necessary.

Example 2

The last item:

sliced = word[-1]
print(sliced)
e

Example 3

Skipping letters with a step of 2:

sliced = word[::2]
print(sliced)
mve

Example 4

A nice trick is to easily revert an array:

sliced = word[::-1]
print(sliced)
eivom

The default step is 1, that is, go forward 1 character of the string at a time.

If you set the step to -1 you have the opposite, go back 1 character at a time beginning at the end of the string.

Watch on Youtube

You can also watch this content on Youtube: