Computer Science · Ch 10 — Tuples and Dictionaries
Summary
Summary
- Tuples are immutable sequences — once a tuple is created, its elements cannot be changed.
- The elements of a tuple are written inside round brackets, separated by commas.
- A sequence of comma-separated values without parentheses is also treated as a tuple by default; a single-element tuple needs a trailing comma, e.g.
(20,). - Tuples are ordered sequences: every element has a fixed position, so indexing (both forward from 0 and backward with negative indices, i.e. two-way indexing as in strings and lists) is used to access elements.
- The
+operator concatenates one sequence (string, list, tuple) to the end of another; the*operator repeats a sequence a specified number of times. - The membership operator
intells whether an element is present in a sequence, andnot indoes the opposite. - Slicing
[start:stop:step]extracts part of a tuple;[::-1]gives the tuple in reverse order. - Tuple manipulation functions and methods:
len(),tuple(),count(),index(),sorted(),min(),max(),sum(). - Tuple assignment unpacks a tuple of values into a tuple of variables (counts must match) — it enables swapping two variables without a temporary variable and returning more than one value from a function.
- A tuple inside another tuple is a nested tuple, useful for storing records such as student details.
- A dictionary is a mapping (non-scalar) data type: a collection of key-value pairs enclosed in curly braces.
- Each key is separated from its value by a colon (
:); consecutive items are separated by commas. - Keys are unique and act as the index for accessing values; looking up a missing key raises
KeyError. …