JuniorCodeOccasionalNot answered yet
What does negative indexing print for 'abyz'[-1]?
Predict the output and explain what a negative index means.
var = 'abyz'
print(var[-1])
print(var[-2])
Determine the output.
Prints z then y. A negative index counts from the end: -1 is the last element, -2 the second-to-last. It is equivalent to var[len(var) - 1]. This works on any sequence — str, list, tuple — and an out-of-range negative index raises IndexError.
- ✗Thinking
-1points at the first element instead of the last - ✗Believing negative indices raise
IndexErrorby default - ✗Forgetting negative indexing works on any sequence, not just strings
- →What does the slice
var[-2:]return for this string? - →When does a negative index actually raise
IndexError?