Tuple Methods
Tuples are immutable, so they have only two methods. Most of what you "do" with a tuple is reading, slicing, and unpacking.
Methods
| Method | Returns |
|---|---|
t.count(x) | How many times x appears. |
t.index(x, start=, stop=) | First index of x; ValueError if absent. |
Built-ins that work on tuples
PYTHON
t = (3, 1, 4, 1, 5, 9, 2) len(t) # 7 min(t), max(t) # 1, 9 sum(t) # 25 sorted(t) # new list — tuple is immutable t1 + t2 # concatenation t * 3 # repetition
Unpack everything
PYTHON
x, y = (3, 4) # exactly two values a, *rest = (1, 2, 3, 4, 5) # rest = [2, 3, 4, 5] *init, z = (1, 2, 3, 4) # init = [1, 2, 3] a, _, c = (1, 2, 3) # _ is the "throwaway" convention
Singleton tuples
PYTHON
not_a_tuple = (42) # int — parens are just grouping one_tuple = (42,) # tuple — trailing comma matters
Named tuples — typed records
PYTHON
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int
p = Point(3, 4)
print(p.x, p.y)
print(p._replace(x=99)) # Point(x=99, y=4)
Tip: Use tuples for "a record of fixed shape" (a point, a date breakdown, a return value with two parts). Use lists for "an unknown-length collection of similar things".
Example
Example
t = (1, 2, 2, 3) print(len(t)) print(t.count(2)) print(t.index(3)) a, b, *rest = t print(a, b, rest)Try it Yourself »
Exercise
How many times does 2 appear in (1, 2, 2, 3)?
t.
(2)
Five letters.
Discussion
Loading…