A tuple is an ordered collection like a list, but it is immutable: once created it cannot be changed. Tuples are used for fixed data such as coordinates, RGB colors, image shapes and database rows.
What You Will Learn
- Creating tuples
- Indexing, slicing and unpacking
- Tuple methods
- When to use a tuple instead of a list
Prerequisites
Creating Tuples
point = (3, 4)
color = (255, 0, 0)
single = (5,) # comma is required
no_brackets = 1, 2, 3
print(type(single), no_brackets)
Explanation: (5) is just the number 5. A one-item tuple needs a trailing comma.
Accessing Items
t = ('a', 'b', 'c', 'd')
print(t[0], t[-1], t[1:3], len(t))
a d ('b', 'c') 4
Tuples Cannot Be Changed
t = (1, 2, 3)
# t[0] = 10 -> TypeError: 'tuple' object does not support item assignment
t = t + (4,) # creates a new tuple
print(t)
(1, 2, 3, 4)
Unpacking
name, age, city = ('Asha', 21, 'Ludhiana')
print(name, city)
first, *rest = (1, 2, 3, 4)
print(first, rest)
Explanation: Unpacking assigns each item to a variable. *rest collects the remaining items into a list.
Asha Ludhiana 1 [2, 3, 4]
Methods
t = (1, 2, 2, 3, 2)
print(t.count(2), t.index(3))
3 3
Tuple vs List
| Feature | List | Tuple |
|---|---|---|
| Syntax | [ ] | ( ) |
| Mutable | Yes | No |
| Speed | Slightly slower | Slightly faster |
| Dictionary key | Not allowed | Allowed |
| Use for | Changing collections | Fixed records |
Returning Multiple Values
def min_max(nums):
return min(nums), max(nums)
low, high = min_max([4, 9, 1])
print(low, high)
Explanation: A function that returns several values actually returns a tuple.
1 9
Common Errors
| Problem | Cause and fix |
|---|---|
TypeError: 'tuple' object does not support item assignment |
Convert to a list, change it, and convert back: tuple(lst). |
ValueError: too many values to unpack |
The number of variables does not match the number of items. |
Practice Exercises
- Swap two values using tuple unpacking.
- Use a tuple of (lat, lon) as a dictionary key.
- Return sum and average from one function.
Interview Questions
Q: Why can tuples be dict keys but lists cannot?
Tuples are immutable and hashable.
Q: How do you make a one-element tuple?
Add a comma: (5,).
Summary
Tuples are ordered and immutable. Use them for fixed data, unpacking and multiple return values.
Next: Python Dictionary · Python Sets
Machine Learning Tutorials, Courses and Certifications