tuple#
tuple is Python’s immutable, ordered sequence. Two natural
uses: a fixed-shape record ((host, port, scheme)) and a
lightweight return-multiple-values vehicle. Hashable when all
elements are hashable, so tuples can sit in set or as a
dict key.
Literal forms.
Form |
Example |
Notes |
|---|---|---|
Standard |
|
Parens plus comma-separated values. |
One-tuple |
|
The trailing comma is required. |
Empty |
|
Empty tuple. |
Implicit |
|
Parentheses are optional in many places. |
Unpacking binds names to positions.
Standard positional unpack.
x, y, z = (1, 2, 3)
Head plus tail with *.
host, *rest = ("a", 1, "tls")
Tuples support indexing, slicing, in, len, and the
boolean / comparison operators. They have no append or
sort because they are immutable; build a new tuple if
needed. Examples assume t = (1, 2, 3).
Operation |
Example |
Result |
|---|---|---|
Index |
|
|
Negative index |
|
|
Slice |
|
|
Concat |
|
|
Sort |
|
|
A namedtuple gives a tuple with field names. Reach for it
when the record’s positions would otherwise be cryptic; reach
for @dataclass when the record needs methods or mutation.
from collections import namedtuple
Target = namedtuple("Target", "host port scheme")
t = Target("example.com", 443, "https")
t.host # "example.com"
Method catalog#
tuple is immutable, so the method surface is tiny. The
operator’s daily work is unpacking and indexing, both of which
are syntax, not method calls.
Method |
Effect |
|---|---|
|
First index of |
|
Number of occurrences. |
namedtuple adds these.
Method |
Effect |
|---|---|
|
Return a new namedtuple with named fields replaced. |
|
Return an |
|
Build a namedtuple from an iterable (classmethod). |
|
Tuple of field names. |
|
Dict of field-name to default value. |
index finds a value’s first position; raises if missing.
("a", "b", "c", "b").index("b")
1
count counts occurrences.
("a", "b", "c", "b").count("b")
2
_replace on a namedtuple returns a new instance with one
field changed; the original is unchanged.
from collections import namedtuple
Target = namedtuple("Target", "host port")
Target("example.com", 80)._replace(port=443)
Target(host='example.com', port=443)
Operator overloading#
tuple implements the immutable-sequence dunders.
Operator |
Dunder |
Returns |
|---|---|---|
|
|
New tuple (concatenation). |
|
|
Repeated tuple. |
|
|
Element-wise equality. |
|
|
Lexicographic less than. |
|
|
Element membership. |
|
|
Indexing and slicing. |
|
|
Length. |
|
|
Iteration. |
|
|
Hash (when elements are hashable). |
|
|
|
A frozen dataclass behaves like a named, hashable record;
__eq__ and __hash__ are auto-generated from the fields.
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: int
y: int
Point(1, 2) == Point(1, 2), {Point(1, 2)} == {Point(1, 2)}
(True, True)
Tuples compare lexicographically, position by position; the operator gets multi-key ordering for free.
sorted([(2, "b"), (1, "z"), (2, "a")])
[(1, 'z'), (2, 'a'), (2, 'b')]
References#
list for the mutable sibling.
Data Structures for
namedtupleand dataclasses.OOP for
@dataclass.