Hone

Lessons · Python · slicing a[start:stop]

A window onto a sequence

seq[start:stop:step] gives the items from start up to but not including stop, without a loop. Negative numbers count from the end.

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

First three, last two, everything but the header, every other item, reversed: slicing does all of them in one expression, on strings as well as lists.

How to think about it

From which position, up to which? Say it as a range first: 'from position 2 up to position 5'. Stop is exclusive, so the length of a slice is stop minus start. Leave a side empty to mean 'from the start' or 'to the end'.

Worked example

days = ["mon", "tue", "wed", "thu", "fri"]
Positions 0 to 4.
print(days[1:3])
["tue", "wed"]: positions 1 and 2, not 3.
print(days[-2:])
["thu", "fri"]: the last two.
print(days[::2])
["mon", "wed", "fri"]: every second one.
print(days[::-1])
Reversed.

Your turn

Everything except the first item.

rest = items[:]

The trap

Slices never raise for out-of-range positions; they return less. Silent, which can hide an off-by-one.

Practise slicing a[start:stop] on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.