โ† Back

Home โ€บ Output practice โ€บ negative indexes and chained slices

Predict the output: negative indexes and chained slices

๐Ÿ”ฎ Predict the outputTopic: stringsDifficulty: easyNo login needed

The snippet

Every answer here follows from two rules โ€” indexes count from -len, and a slice excludes its stop. The hard part is that [::-1] flips the meaning of the other two numbers, and here it is chained with a second slice.

s = "python"
print(s[1:-1], s[::-1][:2], s[-4:-2])

Your prediction

Type exactly what this program prints โ€” one line per print() call:

The output

ytho no th

Verified against CPython 3.11 in this repo's build

Line-by-line explanation

  1. s = "python"
    Six characters: indexes 0โ€“5, or -6 to -1.
  2. s[1:-1]
    Start at 1 (y), stop before -1 (the n) โ†’ ytho. A negative stop counts back from the end; it does not mean "go backwards".
  3. s[::-1][:2]
    [::-1] is the whole string reversed โ†’ "nohtyp"; taking [:2] of *that result* gives no. Slices produce new strings, so chaining works left to right.
  4. s[-4:-2]
    -4 is t, -2 is o; the stop is excluded โ†’ th.
  5. printed together
    print separates arguments with a space โ†’ ytho no th.

The rule you can reuse

s[a:b] includes a, excludes b; a negative index means len + index. Slicing out-of-range never raises โ€” s[:100] just stops at the end, while s[100] raises IndexError.

Why most predictions break here

Reading s[1:-1] backwards, or expecting s[::-1][:2] to give yt. And s[2:2] is the empty string, not an error.

Quick fire

Same rule, two more shapes. Predict first, then open.

Predict this too
print("debug"[2], "debug"[:1], "debug"[-3:])

Output
b d bug

One character, a one-character prefix, and the last three โ†’ b d bug.

Predict this too
print(list(range(10))[::3])
print(list(range(10))[::-1][:2])

Output
[0, 3, 6, 9]
[9, 8]

Every third item from 0 โ†’ [0, 3, 6, 9]; reversed then two โ†’ [9, 8].

Share your result

Challenge a friend โ€” the link contains the question, never the answer:

Copied โœ“

Keep practising this rule

More output questions โ†’ All interactive problems

Questions this page answers

Why does the stop index get excluded?

So that s[:i] + s[i:] always rebuilds the original and len(s[a:b]) is b - a. The empty slice s[3:3] is the same consistency rule.

Do lists behave differently from strings here?

No โ€” indexing and slicing are identical for str, list and tuple. One difference: strings are immutable, so s[0] = "P" raises TypeError while a list allows it.