What will be the output of the following statement ?
``python
print("PythonProgram"[-1:2:-2])
``
What will be the output of the following statement ?
``python
print("PythonProgram"[-1:2:-2])
``
Output: mroPo — obtained by slicing "PythonProgram" from index -1 down to (but not including) index 2, stepping backwards by 2 positions each time.
Marking Scheme
- 11 mark: for the correct output `mroPo` (character sequence and case exactly as traced from the original string).
Hint
Convert -1 to its positive index first (length + (-1)), then step backwards by 2 until you reach (but exclude) index 2.
Quick Oral Answer
Tracing indices 12,10,8,6,4 with a step of -2 from 'PythonProgram' gives the characters m,r,o,P,o, so the output is 'mroPo'.
Analysis & Explanation
This is a classic negative-step string slicing question that tests careful index tracking.
Concept
- The string
"PythonProgram"has indices 0 to 12 (length 13): P(0) y(1) t(2) h(3) o(4) n(5) P(6) r(7) o(8) g(9) r(10) a(11) m(12). - Slice
[-1:2:-2]means: start at index -1 (i.e., index 12), stop before reaching index 2, step -2 (move backwards 2 positions each time).
Index trace
- Start: index 12 → 'm'
- Next: index 10 → 'r'
- Next: index 8 → 'o'
- Next: index 6 → 'P'
- Next: index 4 → 'o'
- Next would be index 2, but since stop=2 is exclusive, the slice stops here.
Result
- Characters collected in order: m, r, o, P, o →
"mroPo".
Exam trap
- Students often forget that a negative start index converts to a positive index internally (start = length + start), and that the stop boundary is strictly exclusive.
Common Mistakes
- 1Forgetting to convert the negative start index -1 to its equivalent positive index before tracing.
- 2Including the character at the stop index (index 2) — the stop value is always exclusive in slicing.
Interesting Facts
Python slicing never raises an IndexError even if indices are out of range — it simply returns as many characters as fit within the valid range.
The general slicing formula s[start:stop:step] works identically for strings, lists, and tuples since they are all sequence types.
Spotted a mistake or something unclear?
Tell us — we fix reported answers fast.
Frequently Asked Questions
How do I convert a negative index to a positive index in Python?
Add the string's length to the negative index. For a string of length 13, index -1 becomes .
Is the stop index in Python slicing inclusive or exclusive?
The stop index is always exclusive — the character at the stop index is never included in the result, regardless of the direction of slicing.