Concepts / Iterating Through Strings

Iterating Through Strings

Using a string's length as an index causes an IndexError because valid indices range from 0 to length - 1, not 0 to length.

  • Programming

The Boundary Problem

When you work through the characters in a string, the string's length tells you how many characters it contains. It does not give you a valid index for one more character. String indices begin at 0 and end at length - 1. The distinction between the number of characters and the largest valid index is the key to avoiding an IndexError.

nextnextnextnextafter final indexfindex 0rindex 1uindex 2iindex 3tindex 4lengthnot a character index
How do character positions map to valid positive indices from 0 through length - 1?

A string with length 5 has valid positive indices 0, 1, 2, 3, and 4. Index 5 is equal to the length, so it lies outside the valid range.

Tracing the Final Position

Finding the final character by counting

Suppose fruit is a string with length 5. Which index identifies its last character?

Count the characters: The string has length 5, so it contains five character positions.

Start indexing at zero: Because the first index is 0, the five valid positive indices are 0 through 4.

Subtract one: The final valid index is length - 1, which is 5 - 1, or 4.

The last character is retrieved with fruit[len(fruit) - 1].

subtract oneuse as indexlength5length - 15 - 1 = 4final characterindex 4
How does subtracting one from the string length identify the final character?

Why the Error Happens

Using the string's length directly as an index asks for a position immediately after the final valid position. For a string whose length is 5, the valid indices stop at 4. Index 5 is not another character position, so using it causes an IndexError.

valid accessoutside valid rangefruitlength 5fruitlength 5length - 1index 4lengthindex 5
What changes when an index equal to the string's length is used?
  • Using the string's length as the final index

    The length is one greater than the largest valid positive index.

    Fix: Use fruit[len(fruit) - 1] or use fruit[-1].

  • Assuming the first positive index is 1

    Positive string indices begin at 0.

    Fix: Count the first character as index 0, so the final positive index is length - 1.

Using Negative Indices

Negative indices provide a direct way to count backward from the end of a string. The index -1 accesses the last character, -2 accesses the second-to-last character, and successive negative indices continue moving backward through the string. This avoids calculating the string's length when the desired character is near the end.

move backwardmove backward-1last character-2second-to-last-3third-to-last
How does -1 locate the last character, and how do successive negative indices move backward?

When the goal is specifically the last character, fruit[-1] is often preferred because it states the goal directly: count one position backward from the end.

Matching Both Index Systems

Positive and negative indices are two ways to refer to the same character positions. For a string with five characters, the first character has positive index 0 and the last character has positive index 4. The same last character can also be reached with negative index -1. Moving one position toward the beginning changes the positive index from 4 to 3 and the negative index from -1 to -2.

same charactersame charactersame charactersame charactersame character0first character-5first character1second character-4second character2third character-3third character3fourth character-2fourth character4last character-1last character
How can positive and negative indices refer to the same character?

Two routes to the final character

How can the final character of fruit be selected in two equivalent ways?

Use the positive index route: The final positive index is one less than the string's length, so use fruit[len(fruit) - 1].

Use the negative index route: The final character is one position from the end, so use fruit[-1].

Compare the references: Both expressions refer to the same final character. The negative-index form is often preferred for readability.

fruit[len(fruit) - 1] and fruit[-1] identify the same final character.

Practice and Check

EASY

A string has length 7. Identify its largest valid positive index. Then write the expression that retrieves its last character using length subtraction and the expression that retrieves it using a negative index.

Hints
  • The largest valid positive index is one less than the length.
  • The negative index for the last character is -1.

What do you think happens?

A string has length 7. Is index 7 a valid index for one of its characters?

  • Yes, because the length is 7
  • No, because the largest valid positive index is 6
Reveal answer

Answer: No, because the largest valid positive index is 6.

Positive indices begin at 0, so a string of length 7 has valid positive indices from 0 through 6. The last character can be selected with length - 1 or with -1.

  • Thinking that length 7 creates valid indices from 0 through 7

    That range contains eight index values, while the string contains seven character positions.

    Fix: Use indices from 0 through length - 1.

  • Using a positive index when the desired position is described from the end

    Counting backward is less direct when the target is the last or second-to-last character.

    Fix: Use -1 for the last character and -2 for the second-to-last character.

Rules to Remember

  1. A string's valid positive indices range from 0 through length - 1.
  2. Using the string's length itself as an index causes an IndexError.
  3. The final character can be retrieved with fruit[len(fruit) - 1].
  4. The final character can also be retrieved with fruit[-1].
  5. Negative indices count backward from the end and are equivalent to corresponding positive indices.

Key Takeaways

  • String indexing starts at 0, so the largest valid positive index is length - 1.
  • Using a string's length as an index goes beyond the final character and causes an IndexError.
  • Use fruit[len(fruit) - 1] to retrieve the final character by calculating its positive index.
  • Use fruit[-1] to retrieve the final character directly from the end.
  • Positive and negative indices can identify the same character position.