liveBook · Manning

Tuple indexing

As explained in Get Programming: Learn to code with Python

Tuple indexing is the operation of retrieving an element from a tuple by its position, including through nested tuple levels.

Tuple indexing retrieves an object by position with square brackets. Counting starts at index 0, so the first object is at position 0 and the second at position 1. section 10.2

Indexing through nested tuples

The expression (3, (3, ("5", 7), 9), "a")[1][1][1] evaluates to 7. First, [1] selects (3, ("5", 7), 9); the next [1] selects ("5", 7); the final [1] selects 7. section 10.2

Remember these related operations:

  • Indexing can return a primitive object or another tuple. section 10.2
  • Apply another index immediately when the selected object is itself a tuple. section 10.2
  • Use slicing with the same rules as string slicing, while remembering that a position may contain another tuple. section 10.2
Figure 10.1. The structure of the tuple (3, (3, ("5", 7), 9), "a"). The dashed lines indicate separate objects in the tuple.

Visualize each nested tuple as a separate object before following the indexing operations. section 10.2

How Get Programming: Learn to code with Python covers it

How deep it goes
Explains zero-based indexing, nested access step by step, and slicing, but does not develop implementation internals.
Examples
Uses indexed literals, nested tuple expressions, quick checks, and a visualization of nested tuple structure.
What it assumes
Assumes familiarity with sequence positions and string indexing while teaching tuple access from basic examples.
What you can do after
Apply tuple indexing and slicing to retrieve values at one or multiple nesting levels.
How it connects
Connects tuples with sequences, strings, slicing, and nested data.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.