INF1-IP: Week 7
Lecture 12 - Collections 2: Tuples and collection operations
- Lecture slides
- Self-guided notebook (right-click → Save As... then remove the .txt part so it is saved as an .ipynb)
Learning outcomes
- Explaining which values can be dictionary keys or set members
- Creating and unpacking tuples
- Accessing and updating two-dimensional lists
- Selecting parts of sequences with slicing
- Looping with
enumerate()andzip() - Using collection methods and comprehensions to process data
Key terms
Click to expand.
Hash
An integer or string that identifies an object, remaining stable over an object's lifetime, with equal objects having equal hashes.
Hashability
The property of a type that determines whether it can be hashed or not. Required for dictionary keys and set members.
Hash collision
When a hash function has assigned two objects the same hash; resolved by checking the objects themselves to see whether they're equal or not.
Tuple
An immutable ordered sequence. It is hashable only if all of its items are hashable.
Unpacking
Assigning the items of a sequence to several names in one statement.
Two-dimensional list
A list whose items are lists, often used as rows of a grid or table.
Slice
A selection from a sequence, specified by start, stop, and optionally step.
Comprehension
An expression that builds a collection by transforming, and optionally filtering, items from an iterable.
New syntax
Click to expand.
hash(value)Returns the hash of a hashable value; raises
TypeErrorfor an unhashable value.(a, b), (a,), ()A two-item tuple, a one-item tuple, and an empty tuple.
first, second = pairUnpacks a two-item sequence into two names.
grid[row][column]Selects an item in a nested list using two indices.
sequence[start:stop:step]Selects items with an exclusive stop boundary and an optional step.
enumerate(items, start=0)Supplies counter-and-item tuples; the counter starts at zero unless specified.
zip(first, second)Supplies tuples of corresponding items, stopping at the shortest iterable by default.
text.split(separator), separator.join(strings)Splits text into strings, or combines strings with a separator.
[expression for item in source if condition]Builds a list with an optional filter. Use curly brackets for a set, or
{key: value for ...}for a dictionary.
Further practice
- Official Python tutorial: Data structures, in particular 5.1.3 List comprehensions; 5.3 Tuples and sequences; and 5.6 Looping techniques.
- W3Schools: Tuples, Slicing strings, and List comprehensions.
- Helsinki Python MOOC: More lists and Tuple.
Lecture 13 - Exception handling and floating-point values
- Lecture slides
- Self-guided notebook (right-click → Save As... then remove the .txt part so it is saved as an .ipynb)
Learning outcomes
- Recognising syntax errors, runtime exceptions, and logic errors
- Handling expected failures with
try...exceptblocks - Using
elseandfinallyto separate success and cleanup - Throwing manual exceptions with
raise - Explaining floating-point approximation and comparing floats with
math.isclose()
Key terms
Click to expand.
Syntax error
Code that breaks Python's grammar and cannot be run as written.
Runtime exception
A problem reported while an operation is running.
Logic error
Code that runs but does not produce the intended behaviour.
Exception handler
An
exceptblock that responds to a matching exception.Propagation
An exception moving back through callers until a matching handler catches it or it crashes the program.
Cleanup
Work done when an operation finishes, even if the operation failed.
Floating-point approximation
The small difference caused by representing a number with a finite binary float.
Tolerance
An acceptable difference when comparing approximate numbers, either relative to magnitude or an absolute amount.
New syntax
Click to expand.
try:Begins a block containing an operation that may raise an exception.
except XError:Handles a matching exception raised by the
tryblock.except XError as error:Also gives the caught exception a name so its message can be inspected.
else:(afterexcept)Runs a block when
trycompletes normally without an exception or early exit.finally:Runs a block as execution leaves the statement, whether or not an exception occurred. When used inside a function, runs before any
returnstatements inside the earliertry...exceptbranches.raise XError(message)Raises an
XErrorwith an explaining message.ZeroDivisionErrorAn exception raised by division by zero.
math.isclose(a, b, rel_tol=..., abs_tol=...)Compares numbers within relative or absolute tolerances, returning a Boolean.
Further practice
- Official Python tutorial: Errors and exceptions and Floating-point arithmetic.
- W3Schools: Try...Except.
- Helsinki Python MOOC: Handling errors.
Tutorial
This week's tutorial time will be used for Assignment 2.
Assessment
Assignment 2 will take place on Friday (30 October), during tutorial time.
For details on the assignment, see Assessment > Assignment 2: Processing Data on Learn.