Lesson explanation
After this lesson, you will be able to:
Tuples group ordered values, like lists, but cannot be changed in place. Parentheses make tuple literals readable; it is the comma that creates a tuple, which is why a one-item tuple needs a trailing comma: ("eu",).
Indexes work as in lists: the first value is at index 0, and -1 reads the last. When you know how many fields a record contains, unpacking assigns them all at once: name, region = record. Python raises ValueError when the number of targets does not match the number of values.
Unpacking can also swap two variables without a separate temporary variable. Unlike a list, record[0] = value raises TypeError: construct a new tuple if you need a changed record.
Tuple indexing uses the same positive and negative positions as list indexing.
endpoint = ("billing", "eu", 443)
print(endpoint[0])
print(endpoint[-1])Output:
billing
443Parentheses alone only group an expression; a comma marks a one-item tuple.
region = ("apac",)
print(type(region).__name__)
print(len(region))Output:
tuple
1Unpacking makes the fields clear without repeated index expressions.
host = ("gateway", 8080, True)
service, port, online = host
print(f"{service}:{port} online={online}")Output:
gateway:8080 online=TruePython packs the right-hand values and assigns them to the targets on the left.
primary = "east"
backup = "west"
primary, backup = backup, primary
print(f"Primary: {primary}")
print(f"Backup: {backup}")Output:
Primary: west
Backup: east| Goal | Python |
|---|---|
| Create a record | ("api", "eu") |
| Create one-item tuple | ("api",) |
| Read an item | record[0] or record[-1] |
| Unpack fields | service, region = record |
| Swap values | a, b = b, a |
| Replace an immutable tuple | Build a new tuple |
("eu") is a string, not a one-item tuple.ValueError.record[1] = "us" raises TypeError.