Concepts / String Indexing and Negative Indices

String Indexing and Negative Indices

A slice with start >= end always produces an empty string, not an error.

  • Programming
Interactive lab

Try it: Indexing and Slicing

How Python indexes a sequence from 0 (or from the end with negative numbers) and how a slice start:stop:step picks positions — with the exact CPython rules for omitted and out-of-range bounds.

How it works

  1. Positions run 0 … len−1; negative positions count back from the end (−1 is the last).
  2. An index outside the string raises IndexError.
  3. A slice resolves start and stop (omitted → the ends; out of range → clamped), then walks by step, stopping before stop.
  4. A negative step walks backwards; a step of 0 is a ValueError.

Default run (7 steps): 'PYTHONIC'[1:6:2]: a slice copies characters from start up to (not including) stop, moving by step. … 'PYTHONIC'[1:6:2] → 'YHN' (positions 1, 3, 5).

Simplified: Works on a short string (up to 16 printable ASCII characters); lists slice by exactly the same rules.

Educational simulation

Loading the simulation…

When a Slice Selects Nothing

A string slice is expected to extract characters between two positions. The important edge case is what happens when the selected range has no forward characters: Python returns an empty string. This is a valid result, not an error.

What do you think happens?

What is the result of fruit[3:3] when fruit is the string banana?

  • An error

  • The character at index 3

  • An empty string

  • The characters in reverse order

Reveal answer
Answer:

An empty string

The slice starts at index 3 and stops before index 3. There is no range of characters to select, so the result is empty.

bananastringindex 0character positionindex 1character positionindex 2character positionindex 3character positionindex 4character positionindex 5character positionindex 6one past the last characterpositionpositionpositionpositionpositionpositionboundary
Which positions are available when the banana examples use indices from 0 through 6?

Tracing the Slice Boundaries

The start and end indices determine the range being considered. A slice with equal boundaries, such as fruit[3:3], has no characters between its start and end. A slice whose start is later than its end, such as fruit[5:2], also produces an empty string. Python does not automatically count backward for this form of slicing.

start 3fruit[3:3]empty stringno characters selectedend 3same boundaryempty stringno backward traversalstart 5fruit[5:2]end 2earlier boundaryreachesproducescomes afterproduces
How does Python move from the start boundary toward the end boundary, and which range exists to select?
Worked example

Three Empty Slice Results

Predict the results of the following slices of banana: fruit[3:3], fruit[5:2], and a slice whose start and end are both beyond the string's length.

  1. 1
    Equal boundaries

    fruit[3:3] has the same start and end index. No range exists between them, so the result is an empty string.

  2. 2
    Start after end

    fruit[5:2] begins after its ending position. In this slicing form, Python does not reverse the characters; it returns an empty string.

  3. 3
    Both boundaries past the string

    A slice whose start and end are both beyond the string's length follows the same empty-range rule when the start equals the end.

Result

All three results are empty strings.

What Empty Means in Python

Definition

An empty string is a valid string with length 0 and no characters. It behaves like any other string: it can be concatenated, compared, iterated over, and passed to functions. Iterating over it does nothing because there are no characters to process.

empty stringlength 0; no charactersconcatenationsupportedstring withcharacterslength greater than 0iterationno characters to processcan be used insupportscan be used in
What distinguishes an empty slice result from a string that contains a character?

Recognizing Reversal Mistakes

Before
fruit[5:2]

Empty string: the start index is greater than the end index, so the ordinary slice does not count backward.

After

fruit[5:2] with a negative step

A negative step is the required direction when the intention is to reverse or move backward.

The expression fruit[5:2] may look as though it should return characters in reverse order. It does not. With the ordinary slice form described here, a start index greater than the end index produces an empty string. Reversal requires a negative step.

fruit[5:2]ordinary sliceempty stringstart greater than endnegative stepbackward directionbackward sliceused for reversalproducesenables
What changes when the intended direction is backward rather than the ordinary forward slice direction?

Debugging Empty Results

empty stringslice resultcompare boundariesstart and endstart equals endno rangecheck intendeddirectionforward or backwarduse negative stepwhen reversal is intendedstart exceeds endordinary slice does notreverseinspectif equalif start is greateraskif backward movement is intended
How can checking the start and end indices reveal why a slice returned an empty string?
  • Common mistake

    Treating an empty slice as an error

    What it looks like

    A slice returns an empty string, so the program is assumed to have failed.

    Why it fails

    Empty strings are valid strings with length 0 and can be used like other strings.

    Do this instead

    Check the start and end indices before deciding that the result is incorrect.

  • Common mistake

    Expecting fruit[5:2] to reverse characters

    What it looks like

    The start index is 5 and the end index is 2, so the result is expected to contain characters in reverse order.

    Why it fails

    The ordinary slice returns empty when the start index comes after the end index.

    Do this instead

    Use a negative step when backward slicing or reversal is intended.

  • Common mistake

    Overlooking equal boundaries

    What it looks like

    fruit[3:3] is expected to contain the character at index 3.

    Why it fails

    The slice selects from index 3 up to, but not including, index 3, leaving no range to select.

    Do this instead

    Recognize start equals end as an empty-range case.

Best practice

When a slice unexpectedly returns an empty string, first compare the start and end indices. If they are equal, there is no range. If the start is greater, the ordinary slice is not moving backward. Then check whether the intended operation was selection in the forward direction or reversal.

Predicting Slice Outcomes

MEDIUM

Predict each result before checking it: fruit[3:3], fruit[5:2], a forward slice that produces pyt, a slice whose equal start and end are both past the string, and a forward slice from index 5 to 6.

Hints
  • First compare the start and end indices.
  • Equal boundaries produce an empty string.
  • A start index greater than the end index produces an empty string in the ordinary slice form.
  • A forward range from index 5 to 6 is not empty.
Slice situationResultReason
start equals endempty stringThere is no range between the boundaries.
start exceeds endempty stringThe ordinary slice does not count backward.
forward rangepytThe range contains characters.
equal boundaries beyond the stringempty stringThe start and end still match, so the selected range is empty.
forward range from index 5 to 6nThe forward range contains one character.

Expected results from the source examples

Key Takeaways

  1. 1
    A slice with start equal to end produces an empty string.
  2. 2
    A slice with start greater than end also produces an empty string in the ordinary slice form.
  3. 3
    An empty string has length 0 and contains no characters, but it remains a valid string.
  4. 4
    An ordinary backward-looking slice such as fruit[5:2] does not reverse characters; a negative step is needed for reversal.
  5. 5
    When debugging an empty result, compare the start and end indices and check whether the intended direction was forward or backward.

At a glance

  • Equal or reversed slice boundaries produce an empty string rather than an error.
  • Empty strings have length 0, contain no characters, and still behave like strings.
  • A negative step is needed when the intention is to move backward or reverse characters.
  • Comparing the start and end indices is the fastest way to diagnose an unexpected empty slice.

Related concepts

More concepts starting with S