Python Tutorial
Python Tuples and Tuple Methods
A tuple is an ordered, immutable sequence. Once created, its items cannot be added, removed or replaced. That makes tuples ideal for fixed records (coordinates, RGB colours, database rows), for returning several values from a function, and as dictionary keys or set members.
This lesson covers creating tuples, the single-item tuple gotcha, packing and unpacking, the two tuple methods count() and index(), named tuples, and how tuples differ from lists.
Creating Tuples
Tuples are written with commas, usually in parentheses: (3, 4). The comma makes the tuple, not the parentheses — so a single-item tuple needs a trailing comma: ("x",). () is the empty tuple and tuple(iterable) converts other sequences.
Packing, Unpacking and Swapping
point = 3, 4 packs values into a tuple; x, y = point unpacks them. The star collects the rest: first, *rest = scores. Functions return multiple values as a tuple. Swapping two variables is simply a, b = b, a.
Tuple Methods and Operations
Tuples have just two methods: count(x) and index(x). They support indexing, slicing, len(), in, concatenation with +, repetition with *, and comparison (item by item). A tuple is immutable, but if it contains a mutable object such as a list, that inner list can still change.
Why Use Tuples
Tuples signal "this data should not change", protect against accidental modification, use slightly less memory than lists, and are hashable (if their items are), so they can be dictionary keys: distances[("Pune", "Mumbai")] = 150. For records with named fields, use collections.namedtuple or typing.NamedTuple.
Examples
Creating tuples and the single-item gotcha
point = (3, 4)
colors = "red", "green", "blue"
single = ("python",)
not_a_tuple = ("python")
print(type(point), type(colors), type(single), type(not_a_tuple))
print(tuple([1, 2, 3]), tuple("abc"), ())
<class 'tuple'> <class 'tuple'> <class 'tuple'> <class 'str'>
(1, 2, 3) ('a', 'b', 'c') ()
Unpacking, star unpacking, swapping and multiple return values
def min_max_avg(values):
return min(values), max(values), sum(values) / len(values)
low, high, avg = min_max_avg([72, 88, 95, 61])
print(low, high, avg)
first, *middle, last = [1, 2, 3, 4, 5]
print(first, middle, last)
a, b = 10, 20
a, b = b, a
print(a, b)
for name, (lat, lon) in [("Pune", (18.52, 73.86)), ("Delhi", (28.61, 77.21))]:
print(f"{name}: {lat}, {lon}")
61 95 79.0
1 [2, 3, 4] 5
20 10
Pune: 18.52, 73.86
Delhi: 28.61, 77.21
count(), index(), operations and immutability
t = (1, 2, 3, 2, 2, 4)
print(t.count(2), t.index(3), t[1:4], len(t), 4 in t)
print((1, 2) + (3,), ("ab",) * 3, (1, 2, 3) < (1, 3))
try:
t[0] = 100
except TypeError as e:
print("TypeError:", e)
record = ("Asha", [90, 85])
record[1].append(99) # the inner list is still mutable
print(record)
distances = {("Pune", "Mumbai"): 150}
print(distances[("Pune", "Mumbai")])
3 2 (2, 3, 2) 6 True
(1, 2, 3) ('ab', 'ab', 'ab') True
TypeError: 'tuple' object does not support item assignment
('Asha', [90, 85, 99])
150
Named tuples for readable records
from collections import namedtuple
from typing import NamedTuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p, p.x, p[1], p._asdict())
class Student(NamedTuple):
name: str
score: int = 0
s = Student("Ravi", 88)
print(s, s.name, s._replace(score=92))
Point(x=3, y=4) 3 4 {'x': 3, 'y': 4}
Student(name='Ravi', score=88) Ravi Student(name='Ravi', score=92)
Common Mistakes
- Writing ("item") for a one-item tuple — it is just a string; add a trailing comma.
- Trying to append to or modify a tuple.
- Assuming a tuple containing a list is fully immutable.
- Using tuples for records with many fields accessed by index instead of namedtuple/NamedTuple.
Key Points to Remember
- Tuples are ordered and immutable; the comma creates them.
- Packing/unpacking, star unpacking and swaps make tuples convenient.
- Only two methods: count() and index().
- Hashable tuples can be dict keys and set members.
- namedtuple / NamedTuple add field names to tuples.
Practice the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.