Playground / Tuples: Comparison and Unpacking

Compare two tuples item by item

Tuples: Comparison and Unpacking

Interactive lab

Try it: Tuples: Comparison and Unpacking

How Python compares tuples lexicographically — the first unequal pair of items decides, a shorter prefix is smaller, int vs str ordering raises TypeError — and how tuple assignment unpacks and swaps values.

How it works

  1. Walk both tuples from index 0 while the items are equal.
  2. At the first difference, that pair alone decides (later items are never looked at); strs compare by code point.
  3. If one tuple runs out first, the shorter one is smaller; ordering an int against a str raises TypeError.
  4. Unpacking checks the count first: too many or too few values raise ValueError before any name is bound.
  5. a, b = b, a builds the right-hand tuple from the old values, then unpacks it into the names.

Default run (4 steps): Evaluate (1, 'pear', 7) < (1, 'plum', 2): compare item by item from index 0. … 'pear' < 'plum' is True (strings compare by code point: 'e' is 101, 'l' is 108), so (1, 'pear', 7) < (1, 'plum', 2) is True.

Simplified: Flat tuples of up to 6 ints or short ASCII strs (no nested tuples, floats or starred targets).

Educational simulation

Loading the simulation…