Functions and Decomposition gave functions clean contracts, but every function so far has taken and returned single scalar values — one
int, one float, one str. Most real problems need a function to return several related values at once (a minimum and a maximum; a fitted slope and intercept), or to work over a fixed, ordered collection of items. Tuples are Python's simplest structured type for exactly this: an immutable, ordered sequence of arbitrarily-typed values. This note also covers ranges, the lazy integer sequence already used informally in for loops, formalising what kind of object range(...) actually produces.Learning objectives. By the end of this note you should be able to:
- construct, index, slice, and concatenate tuples, and correctly apply the "trailing comma" rule for singleton tuples;
- use multiple assignment to unpack a tuple (or a function's tuple-valued return) into several named variables in one statement;
- explain why
rangeobjects occupy constant space regardless of length, and state precisely which sequence operations they do and do not support; - write a function that returns multiple related values as a tuple, and correctly unpack the result at the call site.
In this lesson
- Tuples: an immutable, heterogeneous sequence
- Multiple assignment and unpacking tuples
- Ranges revisited
Before you start
The full lesson, with worked examples and exercise solutions, is for members.
Read the full lessonNew to SelfMadeQuant.com? See membership options or browse the Python for Quantitative Finance syllabus.