all Python 3Tuples (tuple)term
Tuple indexing and slicing
indexing/slicing
Indexing and slicing work just as they do for strings and lists, but the result is a tuple or an item (immutable).
Syntax
t[i] | t[a:b:c]
A slice always yields a tuple, even a one-element one: t[0] is the item itself, while t[0:1] is a tuple holding that item. Slices clamp silently to the real length instead of complaining about out-of-range bounds, whereas t[i] with a bad index raises IndexError immediately. Copying a tuple by slicing is pointless — in CPython t[:] hands back the very same object, not a copy.
Examples
t = (10, 20, 30, 40, 50)
print(t[0])
# → 10
print(t[-1])
# → 50
print(t[1:4])
# → (20, 30, 40)
print(t[::-1])
# → (50, 40, 30, 20, 10)
print(t[::2])
# → (10, 30, 50)
print(t[2:4])
# → (30, 40)
See also
Open in the full glossarydocs.python.orgReport an inaccuracy