Computer Science · Ch 10 — Tuples and Dictionaries
Slicing
10.2.4
Slicing
Slicing extracts a contiguous part of a tuple, exactly as it does for strings and lists. The general form is tuple[start : stop : step] — the slice begins at index start and runs up to but not including index stop, optionally jumping by step.
>>> t = (10, 20, 30, 40, 50, 60, 70, 80)
Basic slices
# elements from index 2 up to index 6 (stop index 7 is excluded)
>>> t[2:7]
(30, 40, 50, 60, 70)
# the whole tuple — from index 0 to len(t)
>>> t[0:len(t)]
(10, 20, 30, 40, 50, 60, 70, 80)
Omitting the start or the stop
# start omitted — the slice begins at index 0
>>> t[:5]
(10, 20, 30, 40, 50)
# stop omitted — the slice runs till the end of the tuple
>>> t[2:]
(30, 40, 50, 60, 70, 80)
Using a step
The third value picks every step-th element:
# every second element, starting at index 0
>>> t[0:len(t):2]
(10, 30, 50, 70)
Negative indices in slices
Negative positions count from the right end, and they can be used inside a slice too:
>>> t[-6:-4]
(30, 40)