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
s = "python"
Six characters: indexes 0โ5, or -6 to -1.s[1:-1]
Start at 1 (y), stop before -1 (then) โytho. A negative stop counts back from the end; it does not mean "go backwards".s[::-1][:2][::-1]is the whole string reversed โ"nohtyp"; taking[:2]of *that result* givesno. Slices produce new strings, so chaining works left to right.s[-4:-2]
-4 ist, -2 iso; the stop is excluded โth.printed togetherprintseparates 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:])Outputb 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 problemsQuestions 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.