Python Slices and Negative Numbers

Python Slices and Negative Numbers

Comment Icon0 Comments
Reading Time Icon2 min read

Python has a rather unique feature regarding indexes in arrays and strings: You can use negative numbers in the ranges.

Suppose we have this string: 

word = ‘SMILE’

The first position is index 0. The second is index 1, and so on:

word[0] gives us S

word[1] gives us M

word[4] gives us E

And we can do ranges (what python calls slices) by putting a start and end separated by a colon like so:

word[1:4] gives us MIL. (The first number is where we start, the second number is where we end, but that one isn’t included. So 1:4 gives us indexes 1, 2, 3.

Want to get from 2 through the end? Keep the colon but leave off the second number.

word[2:] gives us ILE

But what about negative numbers? The python docs give a simple rule for negatives: Add the length of the string to get the actual index. 

So to find where word[-4] is, add the length, 5, to get -1. So word[-4] is the same as word[1], which is M.

And that means each letter in the word SMILE has two indexes, like so:

S has indexes 0 and -5, M has indexes 1 and -4 and so on through E, which has indexes 4 and -1.

Knowing this, you can see how the ranges will work with negative numbers. Tip: Don’t try to fit this on a number line. If you’re math inclined, don’t try to equate this to the modulo function

Let’s try a few then.

word[-4: -1] is the same as word[1:4], which gives us MIL.

Why is this important? Because if you want the last part of a word, you don’t need to check the length, as you would have to do if negative numbers weren’t available. Want the last letter of SMILE? Just use -1 for the index. Want the second from last? Use word[-2] like so:

word[-1] gives us the last letter, E.

word[-2] gives us the second from last letter, L.

And like before, if you want to go through the end of the string, leave off the second number. So to get the last three letters:

word[-3:] gives us ILE

Share this article

About Author

jeffrey

My name is Jeffrey Cogswell and I've written and taught for 30 years and worked full time as a developer in languages such as Python, C#, Java, and C++.

Leave a Reply

Your email address will not be published. Required fields are marked *

Most Relevent