A Visual Guide to Python Slices and Indexes

Posted on August 31, 2020 in Tips & Tricks

A Visual Guide to Python Slices and Indexes

Beginner guide to understanding Python’s slice object.

A Visual Guide to Python Slices and Indexes

Beginner guide to understanding Python’s slice object.

If you’re unsure about how Python indexes and slices strings, this article is for you! First, let’s explore indexes. (Indices for the grammatically correct!).

This is a companion article to my beginner series:

Python Uses Zero-Based Indexes

The first element in a sequence has the index 0. Not 1. This is often a source of confusion!

Although the first character has the index 0, and the last character has index 11, there are in fact 12 characters in this string.

Access an Index using Square Brackets

The character at index position 6 is ‘W’.

Using Negative Index Numbers

Going forwards from 0, W is at index position 6. 
Going backwards from -1, W is at index position -6.

The negative index begins at -1, not zero. Why? Zero is already used for the first character in the forward index!

Enumerating The Sequence of Characters

Python has a very handy enumerate() method. It gives us each element of the character sequence, and the index starting at 0.

This prints out the following in my terminal:

[(0, ‘H’), (1, ‘e’), (2, ‘l’), (3, ‘l’), (4, ‘o’), (5, ‘ ‘), (6, ‘W’), (7, ‘o’), (8, ‘r’), (9, ‘l’), (10, ‘d’), (11, ‘!’)]

This corresponds nicely to the first image, above.

Python’s IndexError

The character at index position 12 is… not there at all!

Trying to access an index position which is outside of the bounds raises an error:

IndexError: string index out of range

Strings are Immutable

You might want to change a letter. Say to change W here to an L. Not in Python! The string is immutable — it can’t be changed.

Instead, we get a TypeError error:

TypeError: 'str' object does not support item assignment

A Slice of Pie

We can get a slice of the string sequence by using slice notation. The slice is given by values inside the square brackets:

[ start_at : stop_before : step ]

The step value is optional and can be left out.

To retrieve the text “lo Wo”, using the information above, we need:

start_at = 3
stop_before = 8
step = nothing

Let’s try this in Python:

The “All The Pie Remaining” Slice

Let’s say we have pie. Real pie. I want you to have the first 5 slices. I want all the remaining slices, 6 to whatever else is left.

start_at = 6
stop_before = :
step = nothing

The notation is:

[6:]

This means: start at 6, continue to the end.

The Start of the Pie Only!

Let’s be less greedy! Let’s just take the first 5 slices of pie:

This means we stop before index 5! Remember, slice at index 0 is also a slice!

The notation is:

[:5]

All The Pie!

There is one final special thing to note about the slice syntax, the *everything* construct:

[:]

This slice captures everything in the sequence!

Using Negative Indexes in The Slice

To get World (without the final !)we could go forwards:

[6:11]

Or we could use the negative index values, too:

[-6:-1]

Going Backwards with a Negative Step

Let’s say we want to eat our pie slice World backwards, like this: dlroW. We could use the positive index values and use a step of -1. Remember the slice syntax:

[ start_at : stop_before : step ]
start_at = index value
stop_before = index value
step = step value

We need to use:

[10:5:-1]

Which gives us:

'dlroW'

Mix and Match Negative and Positive Index Values

This is getting complicated now! And quite crazy!

We’re still interested in retrieving the string dlroW.

[ start_at : stop_before : step ]
start_at = index value
stop_before = index value
step = step value

Earlier we used:

[10:5:-1]

But of course, we can start at 10 or at -2, it’s the same position d!

[-2:5:-1]

And of course, we can choose to stop_before either the positive index value of 5, or the negative index value of -7.

The Slice Object in Python3

We’ve been using literal values so far. Actually typing them out, like [-2:5:-1] . But! Python has the slice object which we can use.

Which results in:

Start: -2
Stop: 5
Step: -1
Slice: slice(-2, 5, -1)
dlroW

I hope you enjoyed this! Check out my article talking about intermediate level string tips and tricks too :)