Negative Indexing for Strings
You can index single characters in strings using the bracket notation. The first character has index 0, the second index 1, and so on. Did you ever want to access the last element in the string? Counting the indices can be a real pain for long strings with more than 8-10 characters.
But no worries, Python has a language feature for this: negative indexing.
Positive Index: The first character has index
0, the second character has index
1, and the
i-th character has index
Negative Index: The last character has index
-1, the second last character has index
-2, and the
i-th last character has index
Instead of start counting from the left, you can also start from the right. Access the last character with the negative index -1, the second last with the index -2, and so on.
x = 'cool' print(x[-1] + x[-2] + x[-4] + x[-3]) # loco
Negative Indexing for Lists
Suppose, you have list
['u', 'n', 'i', 'v', 'e', 'r', 's', 'e']. The indices are simply the positions of the characters in the list.
You can learn more about how to access the last and last n characters of a list or a string in our detailed article.
Related Article: How to Get the Last Element of a Python List?
In summary, there are two ways to index sequence positions, from the left and from the right with positive or negative indices.
Related Code Puzzle
Can you solve this code puzzle in our interactive puzzle app?
Are you a master coder?
Test your skills now!
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.