Tuple operations¶
Tuples are immutable sequences. They support fewer methods than lists because they cannot be modified after creation.
Tuple methods¶
count()¶
Return the number of times a value appears in the tuple.
index()¶
Return the index of the first occurrence of a value. Raises ValueError if the value is not found.
Creating tuples¶
Literal syntax¶
Single-element tuple¶
A trailing comma is required to distinguish a single-element tuple from a grouped expression:
Without parentheses¶
Python recognises tuples by the commas:
The tuple() constructor¶
Convert any iterable to a tuple:
Supported operations¶
Indexing and slicing¶
colours = ("red", "green", "blue", "yellow")
print(colours[0]) # "red"
print(colours[-1]) # "yellow"
print(colours[1:3]) # ("green", "blue")
Concatenation¶
Repetition¶
Membership testing¶
Unpacking¶
Built-in functions¶
numbers = (3, 1, 4, 1, 5)
len(numbers) # 5
min(numbers) # 1
max(numbers) # 5
sum(numbers) # 14
sorted(numbers) # [1, 1, 3, 4, 5] (returns a list)
Comparison¶
Tuples are compared element by element from left to right:
print((1, 2, 3) < (1, 2, 4)) # True
print((1, 2) < (1, 2, 0)) # True (shorter tuple is less)
print((1, 2, 3) == (1, 2, 3)) # True
Named tuples¶
collections.namedtuple¶
Create a tuple subclass with named fields:
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y) # 3 4
print(p[0], p[1]) # 3 4 (indexing still works)
typing.NamedTuple¶
A class-based syntax with type annotations:
from typing import NamedTuple
class Point(NamedTuple):
x: float
y: float
p = Point(3.0, 4.0)
print(p.x, p.y)
Both forms create immutable, hashable objects that support all standard tuple operations.