What is Negative Indexing in Python? : Chris
by: Chris
blow post content copied from Be on the Right Side of Change
click here to view original post
In Python, negative indexing lets you count backwards from the end of a list. So, -1
is the last item, -2
is the second to last, and so on. It’s like starting at the end of a line of people and moving backwards to find someone.
my_list = ['apple', 'banana', 'cherry'] print(my_list[-1]) # Outputs 'cherry', the last item print(my_list[-2]) # Outputs 'banana', the second to last item
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 i-1
.
Negative Index: The last character has index -1
, the second last character has index -2
, and the i
-th last character has index -i
.
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.
(Positive) Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
Element | ‘u’ | ‘n’ | ‘i’ | ‘v’ | ‘e’ | ‘r’ | ‘s’ | ‘e’ |
Negative Index | -8 | -7 | -6 | -5 | -4 | -3 | -2 | -1 |
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!
November 11, 2023 at 07:01PM
Click here for more details...
=============================
The original post is available in Be on the Right Side of Change by Chris
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================
Post a Comment