Guide Python Beginner

11.3 Tuple Indexing and Slicing

Indexing and slicing rules identical to lists and strings, plus the one genuine difference: t[:] on a tuple returns the SAME object rather than a copy, since immutability makes sharing it completely safe.

2 min read

Identical indexing and slicing rules to lists (see 10.3 List Indexing and Slicing) and strings — only the container type, and one copying detail at the end, differs.

Indexing

>>> t = (10, 20, 30, 40, 50)
>>> t[0], t[2]
(10, 30)
>>> t[-1]
50

Nested Tuple Indexing

>>> nested = ((1, 2), (3, 4))
>>> nested[0][1]
2

IndexError

>>> t[10]
Traceback (most recent call last):
IndexError: tuple index out of range

Slicing

>>> t = (10, 20, 30, 40, 50)
>>> t[1:3]
(20, 30)
>>> t[:2], t[2:], t[::2]
((10, 20), (30, 40, 50), (10, 30, 50))
>>> t[::-1]      # reverse
(50, 40, 30, 20, 10)

Copying Tuples

What’s different from lists: because tuples are immutable, CPython optimizes t[:] to return the same object rather than building a new one — there’s no risk in sharing it, since neither copy can ever be mutated. Contrast with 10.3 List Indexing and Slicing, where l[:] on a list always creates a new object.

>>> copy_t = t[:]
>>> copy_t is t     # SAME object -- safe because tuples can't be mutated
True

Quick Interview Answer

“Indexing and slicing on a tuple work exactly like lists and strings — same t[start:stop:step] syntax, direct indexing raises IndexError out of range, slicing never does. The one detail that’s genuinely different from lists: t[:] doesn’t copy anything at all — CPython just hands back the same object, because there’s zero risk in two names sharing an object that can never be mutated. That’s the same optimization strings get for the same reason, and the exact opposite of what happens with a list slice, which always allocates a new list.”

Common Mistakes

  • Expecting t[:] on a tuple to behave like l[:] on a list and produce a distinct copy — is returns True for the tuple case, False for the list case, and that difference is a direct, testable consequence of immutability.
  • Forgetting slicing a tuple returns another tuple, not a list — t[1:3] on (10, 20, 30) gives (20, 30), parentheses and all.
  • Assuming a negative-step slice mutates or reorders the original tuple — t[::-1] returns a brand-new tuple; t itself is untouched, since it couldn’t be touched even if that were the intent.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form