seq[a:b:c] with negative indices & step. Drag, see which elements get picked. Why [::-1] reverses order. An interactive Python Slicing [start:stop:step]…
str, list, tuple, bytes and even range follow exactly the same rules. Misreading the exclusive stop or a negative step raises no error; it just quietly gives one too few or nothing. Bugs like that slip past tests that never check the ends.
A slice is range(start, stop, step) with its bounds tidied first
stop is inclusive, the result is one short seq[1:4] is only indices 1, 2, 3. Want index 4 too? Write seq[1:5]. The upside: seq[:n] always has length n, and seq[:n] + seq[n:] always gives seq back.[::-1] reverses the whole list step -1 walks backwards. Blank start and stop are filled for the step’s direction: start becomes the last index, stop "past the left end". So end to end, backwards.seq[2:999] raises no error though the index is past the end A slice clamps a bound past the end to the edge, so it never raises IndexError. Only a single index seq[i] raises IndexError outside -len(seq) to len(seq) - 1. Handy for "take at most 5": seq[:5] is safe even with only 2 inside.seq[-1:0:-1] loses the first element stop stays exclusive walking backwards, so index 0 is not taken. Changing it to -1 is wrong too: -1 is the last element and the result is empty. Leave stop blank: seq[-1::-1], or just seq[::-1].1:4 inside seq[ ] Layers 1, 2, 3 are cut. Not layer 4: stop is a fence, and Mr. Yusuf stops before touching it. Length of the result = 4 − 1 = 3.2:999 seq[10] raises IndexError at once, but seq[2:999] is safe: the slice clamps 999 to len(seq). A single index is never clamped.seq to a list, say [10, 20, 30, 40, 50] The rules are exactly the same. The difference: a list’s slice is a new list, so seq[:] is the quick way to make a (shallow) copy.