liveBook · Manning

Tuple unpacking

As explained in Python Workout, Second Edition

Unpacking is a Python assignment operation that extracts elements from an iterable into separate targets.

Tuple unpacking is Python assignment syntax that extracts elements from an iterable into separate variables. It is especially useful when enumerate returns an index–value pair or when str.split produces the fields needed by a calculation. section 2.15 section 7.7

Capture an index and character

for index, one_letter in enumerate('abcd'): print(f'{index}: {one_letter}') Each iteration supplies two values, assigned directly to index and one_letter. section 2.15

Apply the same technique when processing structured input:

  • Split an expression and assign its operator and operands: op, first_s, second_s = to_solve.split(). section 7.7
  • Use enumerate inside comprehensions to bind an index and character, optionally starting the index at 1. section 8.31
  • Control uncertain input with split(maxsplit=3), which preserves the remaining text in the final element. section 7.7

How Python Workout, Second Edition covers it

How deep it goes
Demonstrates direct assignment in loops, functions, and comprehensions, while leaving advanced pattern matching mostly unelaborated.
Examples
Uses alphabet iteration, calculator input parsing, and alphabet-to-number dictionary comprehensions.
What it assumes
Assumes familiarity with Python loops, strings, functions, dictionaries, and comprehensions.
What you can do after
Apply unpacking via enumerate and str.split to write compact loops, parsers, and comprehensions.
How it connects
Connects unpacking with enumerate, str.split, comprehensions, dictionaries, and match case.

Also explained in

Compare how 3 books explain tuple unpacking →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.