Hone

Lessons · Python · counting from the end

Counting from the end

A negative index counts from the end: items[-1] is the last item, items[-2] the one before it.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

The latest reading, the last line of a file, the file extension after the final dot: 'last' comes up constantly, and -1 says it without measuring the length.

How to think about it

Reach for -1 whenever you would otherwise write len(x) - 1. Then check the edge: on an empty list, items[-1] raises, exactly like items[0].

Worked example

items = [10, 20, 30]
Three items.
print(items[-1])
30: the last.
print(items[-2])
20.
print(items[len(items) - 1])
30 again, the long way round.
print("report.csv"[-3:])
csv: negative numbers work in slices too.

Your turn

The most recent entry in the log.

latest = log[]

The trap

-0 is 0. There is no negative zero index, so the first item from the end is -1, not -0.

Practise counting from the end on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.