Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is a Negative Indexing in Python?
Negative indexing in Python allows you to access elements from the end of a sequence (string, list, tuple) by using negative numbers. Instead of counting from the beginning (0, 1, 2...), negative indexing counts backwards from the last element (-1, -2, -3...).
Understanding Negative Index Positions
In a string like "Python", the negative indices work as follows ?
Slicing Syntax with Negative Indexing
# Basic slicing syntax sequence[start:stop:step] # Examples with negative indexing sequence[-4:-1] # From 4th last to 2nd last sequence[-5:] # From 5th last to end sequence[:-2] # From beginning to 3rd last sequence[::-1] # Reverse entire sequence
Accessing Single Elements
You can access individual elements using negative indices ?
text = "Python"
print("Last character:", text[-1])
print("Second last character:", text[-2])
print("Third last character:", text[-3])
Last character: n Second last character: o Third last character: h
Slicing with Negative Indices
Extract substrings using negative start and stop positions ?
message = "Hello World!"
print("Original string:", message)
print("Last 6 characters:", message[-6:])
print("From -8 to -3:", message[-8:-3])
print("Every 2nd char from end:", message[::-2])
Original string: Hello World! Last 6 characters: World! From -8 to -3: o Wor Every 2nd char from end: !lroW olleH
Reversing Strings
Use [::-1] to reverse any sequence completely ?
original = "Programming"
reversed_string = original[::-1]
print("Original:", original)
print("Reversed:", reversed_string)
Original: Programming Reversed: gnimmargorP
Negative Indexing with Lists
Negative indexing works with all Python sequences, not just strings ?
numbers = [10, 20, 30, 40, 50]
print("List:", numbers)
print("Last element:", numbers[-1])
print("Last 3 elements:", numbers[-3:])
print("Reversed list:", numbers[::-1])
List: [10, 20, 30, 40, 50] Last element: 50 Last 3 elements: [30, 40, 50] Reversed list: [50, 40, 30, 20, 10]
Common Use Cases
| Operation | Syntax | Description |
|---|---|---|
| Last element | seq[-1] |
Get the last item |
| Last n elements | seq[-n:] |
Get last n items |
| Remove last n | seq[:-n] |
Exclude last n items |
| Reverse | seq[::-1] |
Reverse entire sequence |
Conclusion
Negative indexing in Python provides an intuitive way to access elements from the end of sequences. Use -1 for the last element, [-n:] for the last n elements, and [::-1] to reverse any sequence completely.
