Skip to content

Module 7 · Strings — topic 3 of 22

Negative indexing

Negative indexes count from the end of a string: -1 is the last character, -2 the second last. Learn how negative and positive indexes relate and where negative indexing simplifies code.

Beginner 8 min read·Lesson 84 of 306 in Python Programming

Learning objectives

  • Read characters from the end with negative indexes
  • Convert between negative and positive indexes
  • Use negative indexes for suffix checks

Definition

Negative indexes count from the end of a string: -1 is the last character, -2 the second last. Learn how negative and positive indexes relate and where negative indexing simplifies code.

Introduction

Counting from the start is not always convenient. To reach the last character you would need s[len(s) - 1]. Python lets you count from the end instead with negative numbers: s[-1] is the last character, s[-2] the one before it.

Why it matters

File extensions, check digits, last names and trailing punctuation all sit at the end of strings. Negative indexing reaches them directly and works for strings of any length.

Detailed explanation

Negative indexes are especially helpful when strings have different lengths. A list of file names such as "a.py" and "report_final.py" all have the same last character at index -1, even though their positive indexes differ, so one expression works for every name.

The same idea extends to slices in the next lesson: text[-3:] takes the last three characters of any string, however long it is.

-1 refers to the last character, -2 to the second last, down to -len(s), which is the first character.

Any negative index i refers to the same character as positive index len(s) + i. For a 6-character string, -1 is 5 and -6 is 0.

Indexes below -len(s) raise IndexError, just like positive indexes that are too large.

Negative indexing works for all sequences: lists and tuples too.

There is no -0; 0 always means the first character.

CharacterPYTHON
Positive012345
Negative-6-5-4-3-2-1

Syntax

Python
last = text[-1]
second_last = text[-2]
first = text[-len(text)]
  • -1 is always the last character.
  • Count backwards with larger negative numbers.
  • -len(text) is the first character.

Code examples

From the end

Python
word = "PYTHON"
print(word[-1], word[-2], word[-6])
print(word[-1] == word[len(word) - 1])
Output
N O P
True

Too far back

Python
word = "PYTHON"
try:
word[-7]
except IndexError:
print("-7 is out of range for a 6-letter word")
Output
-7 is out of range for a 6-letter word

More examples

Checking endings with negative indexes

Python
sentences = ["Is it ready?", "It is ready.", "Ready"]
for s in sentences:
if s[-1] == "?":
kind = "question"
elif s[-1] == ".":
kind = "statement"
else:
kind = "no ending punctuation"
print(f"{s!r}: {kind}")
card = "4532015112830366"
print("Last four digits:", card[-4], card[-3], card[-2], card[-1], sep="")
Output
'Is it ready?': question
'It is ready.': statement
'Ready': no ending punctuation
Last four digits:0366

Step-by-step explanation

  • s[-1] reads the final character of each sentence regardless of its length.
  • The if-elif chain classifies the sentence by its ending.
  • card[-4] to card[-1] read the last four digits, the usual masked form of a card number.
  • sep="" prints the pieces without spaces in between.

Expected output

Running “Checking endings with negative indexes” prints exactly:

TextOutput
'Is it ready?': question
'It is ready.': statement
'Ready': no ending punctuation
Last four digits:0366

Practical applications

  • Payment pages show only the last four digits of a card.
  • Text tools check whether a line ends with punctuation.
  • Version strings are parsed from the end, such as the last component of 3.12.1.

Best practices

  • Use s[-1] instead of s[len(s) - 1].
  • Guard against empty strings.
  • Use endswith() (Module 7) for multi-character endings.

Common mistakes

Thinking -0 means the last character

Avoid

last = text[-0]

Prefer

last = text[-1]

-0 is just 0, the first character.

Negative index on an empty string

Avoid

end = line[-1] # line may be empty

Prefer

end = line[-1] if line else ""

An empty string has no last character either.

Key takeaways

  • Negative indexes count from the end; -1 is the last character.
  • Index -i is the same as len(s) - i.
  • Indexes below -len(s) raise IndexError.

Try it yourself

  1. 1
    Print the last three characters of a word using three negative indexes.
  2. 2
    Check whether a word starts and ends with the same letter using index 0 and -1.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

17 questions cover the “Strings” module. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
Practise this module