The GPS position of the Gateway of India is about 18.92° north, 72.83° east. Those two numbers belong together, always in that order, and nobody should change one of them by accident. In Python you'd store them as a tuple: (18.92, 72.83). Python tuples are fixed lists of values, and unpacking is the trick of pulling those values out into separate variables in one line.
You've already used tuples without noticing. for i, name in enumerate(names) unpacks a tuple on every pass, and a, b = b, a swaps two values using one. This lesson shows what tuples are, when to pick one over a list, and every form of unpacking you'll meet.
What you need first: Python lists and Python functions.
Key terms
- Tuple: an ordered collection of values that can't be changed after it's made, written with round brackets:
(18.92, 72.83). - Immutable: can't be changed in place. Tuples and strings are immutable; lists and dictionaries are mutable (changeable).
- Unpacking: assigning the items of a tuple (or list) to several variables at once:
lat, lon = position. - Packing: the opposite, putting several values into one tuple:
position = 18.92, 72.83. - Hashable: a value Python can use as a dictionary key or set item. Tuples of numbers and strings are hashable; lists aren't.
How to create a tuple in Python
point = (3, 4)
student = ("Ahana", 21, "Pune")
empty = ()
print(point, student, empty)
print(type(point))
(3, 4) ('Ahana', 21, 'Pune') ()
<class 'tuple'>
It's actually the comma that makes a tuple, not the brackets. The brackets are only there to make it readable. This is why a tuple with one item needs a trailing comma:
not_a_tuple = (5)
one_item = (5,)
also_tuple = 5,
print(type(not_a_tuple), type(one_item), type(also_tuple))
<class 'int'> <class 'tuple'> <class 'tuple'>
(5) is just the number 5 in brackets, the same as in maths. Everyone forgets the comma at least once.
Reading a tuple
Indexing, slicing, len, in and looping all work exactly as they do for lists:
marks = (72, 88, 95, 64)
print(marks[0], marks[-1])
print(marks[1:3])
print(len(marks), 95 in marks)
print(marks.count(88), marks.index(95))
72 64
(88, 95)
4 True
1 2
Tuples have only two methods, count and index, because every other list method changes the list.
Tuples can't be changed
Try to change an item and Python refuses:
city = ("Mumbai", 18.92, 72.83)
city[0] = "Pune"
TypeError: 'tuple' object does not support item assignment
To get a different tuple, build a new one. You can join tuples with +:
city = ("Mumbai", 18.92, 72.83)
city = ("Pune",) + city[1:]
print(city)
('Pune', 18.92, 72.83)
One subtle point: a tuple can hold a mutable object like a list, and that list can still change. The tuple only fixes which objects it holds, not what's inside them.
team = ("India", ["Rohit", "Virat"])
team[1].append("Bumrah")
print(team)
('India', ['Rohit', 'Virat', 'Bumrah'])
Tuple vs list in Python
| List | Tuple | |
|---|---|---|
| Brackets | [1, 2, 3] | (1, 2, 3) |
| Can change | Yes: append, remove, sort | No |
| Dictionary key or set item | No | Yes, if its items are hashable |
| Typical use | Many items of the same kind that grow or shrink | A fixed group of related values |
| Example | All marks in a class | One (name, roll number, city) record |
A good rule: use a list for "many of the same thing" and a tuple for "one thing with several parts". A list of 60 students' marks changes as results come in. A single date as (2026, 12, 3) should never change.
Tuples also make good dictionary keys. A list can't do this:
distances = {
("Mumbai", "Pune"): 148,
("Delhi", "Agra"): 233,
}
print(distances[("Delhi", "Agra")])
233
Tuples use a little less memory and are a little faster to create than lists, but that's rarely a reason to choose one. Pick based on whether the data should change.
Unpacking a tuple
Unpacking puts each item into its own variable:
position = (18.92, 72.83)
lat, lon = position
print(f"Latitude {lat}, longitude {lon}")
Latitude 18.92, longitude 72.83
The number of variables must match the number of items, or Python raises an error:
lat, lon = (18.92, 72.83, 11.0)
ValueError: too many values to unpack (expected 2)
Swapping two variables
The right side builds a tuple (b, a) first, then unpacks it into a and b. No temporary variable is needed:
a, b = 10, 20
a, b = b, a
print(a, b)
20 10
Unpacking in loops
When you loop over pairs, unpack them straight in the for line:
scores = [("Ahana", 88), ("Rohan", 72), ("Meera", 95)]
for name, score in scores:
print(f"{name} scored {score}")
Ahana scored 88
Rohan scored 72
Meera scored 95
This is exactly what happens with enumerate() and zip(), and with .items() on a dictionary: each gives you tuples to unpack.
Collecting the rest with *
A starred name collects "everything else" into a list:
first, *middle, last = [64, 72, 88, 91, 95]
print(first, middle, last)
top, *others = ("Gold", "Silver", "Bronze", "Fourth")
print(top, others)
64 [72, 88, 91] 95
Gold ['Silver', 'Bronze', 'Fourth']
Use _ for values you don't need. It's an ordinary name, but it tells readers "ignore this":
name, _, city = ("Ahana", 21, "Pune")
print(name, city)
Ahana Pune
Returning several values from a function
A function that seems to return two values actually returns one tuple, which the caller unpacks:
def min_max(numbers):
return min(numbers), max(numbers)
result = min_max([72, 88, 95, 64])
print(result)
low, high = min_max([72, 88, 95, 64])
print(low, high)
(64, 95)
64 95
Named tuples: tuples with labels
student[2] doesn't say what the third item is. A named tuple lets you use names instead of positions, while staying a tuple:
from collections import namedtuple
Student = namedtuple("Student", ["name", "age", "city"])
s = Student("Ahana", 21, "Pune")
print(s.name, s.city)
print(s[1])
print(s)
Ahana Pune
21
Student(name='Ahana', age=21, city='Pune')
For records with many fields, or ones that need methods, a dataclass is usually the better choice; it's covered in the object-oriented module.
Where tuples are used
- Data from databases: Python database libraries such as
sqlite3return each row as a tuple. - Shapes in NumPy and pandas:
df.shapegives(rows, columns), such as(1000, 12). - Coordinates and colours:
(x, y)points and(255, 128, 0)RGB colours in Matplotlib. - Dictionary keys that combine two things, like a (city, date) pair.
Common mistakes
- Forgetting the comma in a one-item tuple:
("Pune")is a string. - Trying to append to a tuple. Use a list if the data grows.
- Unpacking the wrong number of items. Use
*restwhen the length varies. - A trailing comma by accident:
total = 5,makestotalthe tuple(5,), and later maths fails with a confusingTypeError.
Practice
- Create a tuple of the days of the weekend and print how many there are and whether "Sunday" is in it.
Show the answer
weekend = ("Saturday", "Sunday")
print(len(weekend), "Sunday" in weekend)
2 True
- What is the type of each value:
a = (1),b = (1,),c = 1, 2,d = ()?
Show the answer
a is an int, because brackets alone don't make a tuple. b, c and d are all tuples: b and c have commas, and () is the special way to write an empty tuple.
- Given
record = ("TN-07", "Chennai", 2019, "Petrol"), unpack it intoplate,city,yearandfuel, and print"TN-07 from Chennai".
Show the answer
record = ("TN-07", "Chennai", 2019, "Petrol")
plate, city, year, fuel = record
print(f"{plate} from {city}")
TN-07 from Chennai
- Write a function
stats(marks)that returns the total, the average rounded to 1 decimal place, and the highest mark. Unpack the result.
Show the answer
def stats(marks):
total = sum(marks)
return total, round(total / len(marks), 1), max(marks)
total, average, highest = stats([72, 88, 95, 64])
print(total, average, highest)
319 79.8 95
319 ÷ 4 = 79.75, which rounds to 79.8.
- A list of
(city, temperature)pairs is given. Print the hottest city using a loop with unpacking.
temps = [("Delhi", 41), ("Shimla", 24), ("Chennai", 37), ("Jaipur", 44)]
Show the answer
temps = [("Delhi", 41), ("Shimla", 24), ("Chennai", 37), ("Jaipur", 44)]
hottest, highest = temps[0]
for city, temp in temps[1:]:
if temp > highest:
hottest, highest = city, temp
print(hottest, highest)
Jaipur 44
The short version is max(temps, key=lambda pair: pair[1]), covered in lambda, map, filter and sorted.
Interview questions
What is the difference between a list and a tuple?
A list is mutable and written with []; a tuple is immutable and written with (). Because tuples can't change, a tuple of hashable items can be a dictionary key or set member. Lists suit collections that change; tuples suit fixed records.
Can a tuple be changed if it contains a list?
The tuple itself can't change: it always holds the same objects. But a list inside it can be changed in place, for example with append. Such a tuple is also no longer hashable, so it can't be a dictionary key.
How does a, b = b, a work?
The right side is evaluated first and packed into a tuple (b, a). That tuple is then unpacked into a and b. Because the old values are saved in the tuple before anything is assigned, no temporary variable is needed.
Key takeaways
- A tuple is an ordered, unchangeable collection; the comma makes it, so a single item needs
(5,). - Use a list for many items of the same kind, and a tuple for one record with several parts.
- Tuples of hashable values can be dictionary keys; lists can't.
- Unpacking assigns items to variables:
lat, lon = position.*restcollects extras and_marks values you'll ignore. - Functions that "return several values" return one tuple.
Frequently asked questions
Why does Python have both tuples and lists?
Because some data shouldn't change. A tuple protects a fixed record from accidental edits and can be used as a dictionary key, while a list is built for adding and removing items.
How do I change a value in a tuple?
You can't change it in place. Make a new tuple, for example by slicing and joining, or convert it with list(t), change the list, and turn it back with tuple(...).
Is a tuple faster than a list?
Slightly, for creating and for memory, but the difference rarely matters in real programs. Choose based on whether the data should change, not speed.
What to learn next
- Remove duplicates and compare groups with Python sets and set operations.
- Build lists, dictionaries and sets in one line with Python comprehensions.
- Revise the other key-based collection in Python dictionaries.