7. Tuples#
This chapter introduces tuples, a built-in sequence type, and shows how tuples work alongside lists and dictionaries. You will practice tuple assignment and the packing and unpacking operators used with variable-length argument lists.
By the end of this chapter, you will be able to:
Create tuples using literals, packing, and the tuple() constructor
Unpack tuples (including starred unpacking) in assignments and loops
Use zip(), enumerate(), divmod(), and other tuple-aware built-ins
Choose between tuples and lists based on mutability needs
Return multiple values from a function using tuples
One note: There are two common pronunciations of “tuple”. Some people say “tuh-ple” (rhymes with “supple”). In programming, many people say “too-ple” (rhymes with “quadruple”).
What is a Tuple?
A tuple is a sequence of values.
The values can be any type.
The values in a tuple are indexed by integers, so tuples feel a lot like lists.
When a function returns multiple values, it returns a tuple.
Tuples are hashable when all of their elements are hashable.
Tuples are commonly used to group related values together. For example, a latitude and longitude pair naturally belongs together:
location = (42.3601, -71.0589)
A tuple is a sequence, just like list. When the data belongs together and shouldn’t change - like a coordinate, a date, or a name/age pair - use a tuple. If you need to add, remove, or modify items, use a list.
Feature |
Tuple |
List |
|---|---|---|
Syntax |
|
|
Mutable |
No |
Yes |
Hashable |
Yes (conditional) |
No |
Methods |
2 ( |
Many |
Use case |
Fixed data, records |
Collections that change |
Performance |
Faster |
Slower |
Immutability
Tuples are immutable, which is the key characteristic of tuples. Once created, items cannot be added, removed, or changed within a tuple, but new tuples can be created as a result of operations. That’s why tuples lack list methods that modify in place, like append and remove.
If you try to modify a tuple with indexing, Python raises a TypeError.
%%expect TypeError
invoice_key = ("INV-2026-0142", "ACME", "2026-02-28")
print("Invoice key[0]:", invoice_key[0])
invoice_key[0] = "INV-2026-0143" # Tuple does not support item assignment
Invoice key[0]: INV-2026-0142
TypeError: 'tuple' object does not support item assignment