liveBook · Manning

Nested tuple

As explained in Get Programming: Learn to code with Python

A nested tuple is a tuple whose elements include one or more tuples as subordinate collections.

A nested tuple is a tuple containing another tuple as one of its elements. Tuples can hold any kind of object, including several levels of subordinate tuples. section 10.2 section 10.3

Index through the levels

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

When working with nested tuples:

  • Use indexing from position 0, remembering that an index may return another tuple rather than a final value. section 10.2
  • Chain indexing operations to reach values deeper inside the structure. section 10.2
  • Use slicing to select a range of outer elements, while checking whether those elements are themselves tuples. section 10.2
  • Organize related results as a tuple of tuples, such as separate tuples for names and phone numbers read from a file. section 23.1

A practical data shape

A file-reading function can return ((Friend1 Name, Friend2 Name, ...), (Friend1 phone, Friend2 phone, ...)). The outer tuple returns both collections as one value, while each inner tuple stores one kind of information. section 23.1

Figure 10.1. The structure of the tuple (3, (3, ("5", 7), 9), "a"). The dashed lines indicate separate objects in the tuple.

Use the structure diagram to see each nested tuple as a separate object and trace the path taken by chained indexing. section 10.2

How Get Programming: Learn to code with Python covers it

How deep it goes
Explains construction, length, indexing, slicing, chained access, and file-based organization, but stops short of advanced tuple internals.
Examples
Demonstrates deeply nested numeric and string tuples, quick-check expressions, and names-and-phone-numbers parsed from alternating file lines.
What it assumes
Assumes basic tuple and sequence operations while teaching nested structure and multi-level access through small expressions.
What you can do after
Apply it via Python indexing and slicing to retrieve values or organize related file data into one return value.
How it connects
Connects nested tuples with tuples, indexing, slicing, functions, file input, and return values.

Also explained in

Compare how 2 books explain nested tuple →

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.