Tuples are ordered, immutable sequences — faster and safer than lists for fixed data.
Python Tuples
Tuples are like lists but immutable — you cannot change them after creation. Use tuples for data that should not change.
Syntax
<pre><code># Creating tuples
coordinates = (10, 20)
person = ("Alice", 25, "Engineer")
single = (42,) # Single element needs trailing comma!
# Accessing
print(coordinates[0]) # 10
print(person[-1]) # Engineer
# Unpacking
x, y = coordinates
name, age, job = person
# Tuple methods
print(coordinates.count(10)) # 1
print(coordinates.index(20)) # 1
# Why use tuples?
# 1. Faster than lists
# 2. Can be used as dictionary keys
# 3. Protect data from accidental modification
# Named tuples (more readable)
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y) # 3 4
</code></pre>
Revision Notes
• () or no brackets; immutable
• Single element tuple needs trailing comma: (1,)
• Unpacking: a, b = (1, 2)
• count() and index() are only tuple methods
• Use as dict keys; hashable unlike lists
You are given a list of tuples, each containing a student name and their score: [("Alice", 85), ("Bob", 92)]. Write a function called print_scores(students) that unpacks each tuple and prints "Name: <name>, Score: <score>" for every student.
Input:
[("Alice", 85), ("Bob", 92)]
Output:
Name: Alice, Score: 85
Name: Bob, Score: 92
Show Hint
Use a for loop with tuple unpacking: for name, score in students: