LearnWave
Learn it. Master it.

Tuples and Dictionaries

Tuple functions, assignment and nesting

Unpack a tuple into variables.

Functions and methods for tuples: len(); tuple(), which makes an empty tuple or turns a string, list or range into a tuple; count(); index() (a ValueError if the element is absent); min(), max(), sum(); and sorted(), which returns a new sorted list (not a tuple): sorted((9, 4, 7)) gives [4, 7, 9].

Tuple assignment assigns each element of a tuple on the right to a variable on the left, in one go: (x, y) = (10, 20) sets x to 10 and y to 20. A record can be unpacked the same way: (name, rollNo, subject) = record. The number of variables must match the number of elements: (x, y) = (1, 2, 3) gives a ValueError. The right side is worked out first: (a, b) = (3 + 4, 5 * 2) sets a to 7 and b to 10.

This gives a neat way to swap two values without a temporary variable: (x, y) = (y, x).

A nested tuple holds tuples. Student records, for example: st = ((201, 'Meera', 88), (202, 'Kabir', 93)). st[i] is the i-th record, and st[i][1] that student's name: st[0][1] is 'Meera'.

Functions use tuples to return several values: return (area, circumference). And numbers typed one by one can be collected into a tuple: numbers = numbers + (num,).

(a, b) = (b, a) swaps.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.