L2·Control & Collections

🔗Tuples

Immutable ordered sequences — great as keys.

tupleimmutableunpacking

§ 1Immutable = hashable

Tuples of hashables can be dict keys or set members. Lists cannot.

§ 2Unpacking

a, b, c = (1, 2, 3). Star: a, *rest = [1,2,3,4] → rest=[2,3,4].

§ 3One-element tuple

(1,) not (1) — the trailing comma matters.

Example

1point = (3, 4)
2x, y = point
3print(x + y)
4
5first, *rest = [1,2,3,4,5]
6print(first, rest)

Try it live · Python runs in your browser

Loading playground…

Checkpoint quiz

Question 1 / 2
Which is a 1-tuple?
Prev
Lists
Next
Dictionaries