liveBook · Manning

Tuple

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

A tuple is an immutable ordered collection of Python elements.

A tuple is an immutable ordered collection created by placing commas between values. Parentheses make the grouping explicit, and indexing retrieves its elements. section 22.1.1

Create, index, and unpack a tuple

>>> state = (1, 'X') >>> state[0] 1 >>> state[1] = 'O' TypeError: 'tuple' object does not support item assignment Tuples also support unpacking: `cell, player = state`. This makes a compact return value useful when a function produces several related values. section 22.1.1 section 14.3.4

Tuples appear naturally when:

  • `zip()` pairs corresponding elements from sequences, producing tuples such as `('a', '1')`; it stops when the shortest input ends. section 19.1.2
  • A CSV parser zips headers with field values, then converts the tuple pairs into a dictionary record. section 19.1.2
  • Multiple counters can be initialized and assigned in one statement: `lines, words, bytes = 0, 0, 0`. section 6.3.2

Use a tuple when related values should travel together but must not be accidentally changed. A named tuple extends the same immutable behavior with named fields, combining tuple indexing with dictionary-like access such as `state.cell`. section 22.1.2 section 22.1.1

>>> pairs = list(zip(groomsmen, bridesmaids))
>>> pairs
[('G', 'B'), ('G', 'B'), ('G', 'B')]
>>> len(pairs)
3

See `zip()` produce a list of paired tuples from two sequences. section 19.1.2

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Explains creation, indexing, unpacking, immutability, zip-generated pairs, and named tuples, stopping short of deeper implementation internals.
Examples
Demonstrates word stemming, CSV records, counter initialization, and Tic-Tac-Toe state with runnable REPL output.
What you can do after
Apply tuples to return, pair, unpack, index, and protect related Python values from reassignment.
How it connects
Connects tuples with lists, dictionaries, unpacking, zip, named tuples, regular-expression matches, enumeration, and type hints.

Also explained in

Compare how 15 books explain tuple →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.