Python course · Module 4: Data structures · Lesson 16 of 63
Quick answer: A Python tuple is an ordered collection like a list, but it cannot be changed after it is made (it is immutable): product = ("Pen", 60, "Blue"). You read items by index, as with a list, but product[1] = 75 raises a TypeError. A tuple with one item needs a comma: ("Pen",). Unpacking puts the items into separate variables in one line: name, price, colour = product.
In this lesson you will learn:
- how to create a Python tuple, including the empty and one-item tuple
- what “immutable” means in practice and how to work around it
- how to unpack a tuple, and how star unpacking (
*rest) collects the leftover items - how swapping and returning several values use tuples behind the scenes
Before you start: finish Lesson 15, Python Lists and List Methods: Indexing, Slicing, Sorting and Copying, because tuples use the same indexes and slices. You will also use multiple assignment from Lesson 5, Python Variables: Naming Rules and Examples. All examples were tested on Python 3.14.6 and behave the same on Python 3.15.2, the newest release on python.org, except for one longer error message noted below.
Table of Contents
Create a tuple
A tuple is written as values separated by commas, usually inside round brackets.
product = ("Pen", 60, "Blue")
point = 3, 4
empty = ()
print(product)
print(point)
print(type(point))
print(len(product), len(empty))
print(product[0], product[-1])
print(product[0:2])
('Pen', 60, 'Blue')
(3, 4)
<class 'tuple'>
3 0
Pen Blue
('Pen', 60)
Indexing, negative indexes, slices and len() work exactly as with lists; a slice of a tuple is a new tuple. Look at point = 3, 4: there are no brackets, but Python still made a tuple. The Built-in Types page explains: “it is actually the comma which makes a tuple, not the parentheses.” That is why price = 1,500 in Lesson 6, Python Numbers: int, Float vs Decimal and Rounding gave a tuple instead of a number. The brackets are required for the empty tuple (), and where the commas could mean something else, for example inside a function call: print((3, 4)) prints one tuple, while print(3, 4) prints two numbers.
The one-item tuple needs a comma
Because the comma makes the tuple, brackets around one value do nothing:
not_a_tuple = ("Pen")
one_item = ("Pen",)
also_one = "Pen",
print(type(not_a_tuple), not_a_tuple)
print(type(one_item), one_item)
print(type(also_one), also_one)
print(len(one_item))
<class 'str'> Pen
<class 'tuple'> ('Pen',)
<class 'tuple'> ('Pen',)
1
("Pen") is just the string "Pen" in brackets, like (2 + 3) in a sum. Add a trailing comma to get a tuple with one item. The Python tutorial calls this rule “Ugly, but effective.” Python prints a one-item tuple with the comma, too: ('Pen',).
Tuples are immutable
Once a tuple exists, you cannot replace, add or remove items:
product = ("Pen", 60, "Blue")
product[1] = 75
Traceback (most recent call last):
File "/home/learner/python-course/err1_change_tuple.py", line 2, in <module>
product[1] = 75
~~~~~~~^^^
TypeError: 'tuple' object does not support item assignment
Tuples also have no append(), remove() or sort() methods:
sizes = ("S", "M", "L")
sizes.append("XL")
Traceback (most recent call last):
File "/home/learner/python-course/err2_append_tuple.py", line 2, in <module>
sizes.append("XL")
^^^^^^^^^^^^
AttributeError: 'tuple' object has no attribute 'append'
On Python 3.15 the last line is longer: AttributeError: 'tuple' object has no attribute 'append'. Did you mean to use a 'list' object?. The What’s New in Python 3.15 page lists this hint under improved error messages.
Working with a tuple you want to “change”
You can always build a new tuple and store it under the same name, or turn the tuple into a list, change the list, and turn it back:
product = ("Pen", 60, "Blue")
product = (product[0], 75, product[2])
print(product)
sizes = ("S", "M", "L")
sizes = sizes + ("XL",)
print(sizes)
sizes_list = list(sizes)
sizes_list.remove("S")
sizes = tuple(sizes_list)
print(sizes)
print(sizes.count("M"), sizes.index("L"))
('Pen', 75, 'Blue')
('S', 'M', 'L', 'XL')
('M', 'L', 'XL')
1 1
+ joins two tuples into a new one (note the comma in ("XL",)). list() and tuple() convert between the two types. Tuples have only two methods, count() and index(), which work as they do for lists.
One detail: a tuple cannot change which items it holds, but if one item is a list, that list can still change.
order = ("Order 17", ["Pen", "Notebook"])
order[1].append("Ruler")
print(order)
('Order 17', ['Pen', 'Notebook', 'Ruler'])
The tutorial says it is “possible to create tuples which contain mutable objects, such as lists”. The tuple still holds the same list; only the list’s contents changed.
Unpacking a tuple
Unpacking takes the items out of a tuple and puts each one in its own variable:
product = ("Pen", 60, "Blue")
name, price, colour = product
print(name)
print(price)
print(colour)
print(f"{name} costs {price} rupees.")
Pen
60
Blue
Pen costs 60 rupees.
The first name gets the first item, the second name the second item, and so on. This is much easier to read than product[0], product[1] and product[2]. The number of names must match the number of items. Too few names:
product = ("Pen", 60, "Blue")
name, price = product
Traceback (most recent call last):
File "/home/learner/python-course/err3_unpack_many.py", line 2, in <module>
name, price = product
^^^^^^^^^^^
ValueError: too many values to unpack (expected 2, got 3)
Too many names gives ValueError: not enough values to unpack (expected 4, got 3). Read the error as “Python expected this many names to fill, but got this many values”.
Star unpacking: collect the rest
Put * before one name, and that name collects all the items that are left over, as a list:
scores = (91, 85, 77, 64, 58)
first, *others = scores
print(first, others)
*others, last = scores
print(others, last)
top, *middle, bottom = scores
print(top, middle, bottom)
only, *rest = ("Pen",)
print(only, rest)
91 [85, 77, 64, 58]
[91, 85, 77, 64] 58
91 [85, 77, 64] 58
Pen []
The names without a star are filled first, from the left and from the right; the starred name gets everything in between. The language reference says the starred name receives “A list of the remaining items” and adds “the list can be empty”, which the last line shows. Only one starred name is allowed: *best, *worst = scores gives SyntaxError: multiple starred expressions in assignment.
Swapping and packing
Writing several values with commas packs them into a tuple. Unpacking does the opposite. Together they give the one-line swap you met in Lesson 5:
left = "Pen"
right = "Notebook"
pair = left, right
print(pair)
left, right = right, left
print(left, right)
('Pen', 'Notebook')
Notebook Pen
right, left on the right side packs the two current values into a tuple first; then the tuple is unpacked into left and right. The tutorial puts it this way: “multiple assignment is really just a combination of tuple packing and sequence unpacking.”
Unpacking in a for loop
A list of tuples is a common way to store records, such as product names with prices. Unpack each tuple right in the for line:
products = [("Notebook", 450), ("Pen", 60), ("Backpack", 3200)]
total = 0
for name, price in products:
print(f"{name:<10}{price:>6}")
total += price
print(f"{'Total':<10}{total:>6}")
Notebook 450
Pen 60
Backpack 3200
Total 3710
On each pass, one tuple is unpacked into name and price. This is the same thing that happened with for index, product in enumerate(products): in Lesson 12, Python for Loops and range(): Lists, Strings and enumerate(): enumerate() gives a pair on every pass. The :<10 and :>6 format specs from Lesson 7 line up the columns.
Returning several values
Some functions give back a tuple so that you can receive several results at once. The built-in divmod() returns “a pair of numbers consisting of their quotient and remainder”, according to the built-in functions page. It solves the minutes-to-hours task from Lesson 14, Python Exercises for Beginners: Level 1 Practice Set and Number Guessing Game in one line. Your own functions can do the same; def and return are taught properly in Lesson 22, so read the middle part as a preview. It uses two more built-in functions: min() gives the smallest item of a list and max() the largest.
print(divmod(135, 60))
hours, minutes = divmod(135, 60)
print(f"{hours} hours and {minutes} minutes")
def cheapest_and_dearest(prices):
return min(prices), max(prices)
result = cheapest_and_dearest([450, 60, 3200, 900])
print(result)
low, high = cheapest_and_dearest([450, 60, 3200, 900])
print(f"Prices go from {low} to {high} rupees.")
(2, 15)
2 hours and 15 minutes
(60, 3200)
Prices go from 60 to 3200 rupees.
return min(prices), max(prices) packs two values into one tuple. Store it as one value (result) or unpack it straight away (low, high). The Programming FAQ recommends this: “Your best choice is to return a tuple containing the multiple results.”
Tuple or list?
| Feature | List | Tuple |
|---|---|---|
| Brackets | [1, 2] | (1, 2) or 1, 2 |
| Can change after creation | yes | no |
| Methods | many (append, sort, …) | only count and index |
| Typical use | many items of the same kind | a fixed group of related values |
The tutorial describes the usual split: tuples “usually contain a heterogeneous sequence of elements” (different kinds of values, like a name and a price), while list elements “are usually homogeneous” (the same kind, like many prices). Use a list when the collection will grow or change, and a tuple for a fixed record that should not be changed by accident. Lesson 17 shows one more reason: a tuple can be a dictionary key, and a list cannot.
Try it yourself
Exercise 1: Colour codes
Store the colour orange as the tuple (255, 165, 0). Unpack it into red, green and blue and print Red 255, green 165, blue 0.
Exercise 2: First, middle and last
Make marks = (72, 85, 64, 91, 58). Use star unpacking to put the first mark, the middle marks and the last mark into three variables, and print them.
Exercise 3: Who passed?
Make results = [("Ali", 72), ("Sara", 55), ("Hina", 91), ("Omar", 48)]. Loop over it with unpacking and print a line for each student with a mark of 60 or more.
Solutions
Solution 1
orange = (255, 165, 0)
red, green, blue = orange
print(f"Red {red}, green {green}, blue {blue}")
Red 255, green 165, blue 0
Three names on the left match the three items in the tuple.
Solution 2
marks = (72, 85, 64, 91, 58)
first, *middle, last = marks
print("First:", first)
print("Middle:", middle)
print("Last:", last)
First: 72
Middle: [85, 64, 91]
Last: 58
The starred name collects the middle marks, as a list.
Solution 3
results = [("Ali", 72), ("Sara", 55), ("Hina", 91), ("Omar", 48)]
for name, mark in results:
if mark >= 60:
print(f"{name} passed with {mark}.")
Ali passed with 72.
Hina passed with 91.
Each tuple is unpacked into name and mark in the for line, and the if keeps only marks of 60 or more.
Common mistakes
- Forgetting the comma in a one-item tuple.
("Pen")is a string, not a tuple. Write("Pen",). - Trying to change a tuple.
product[1] = 75givesTypeError: 'tuple' object does not support item assignment. Build a new tuple, or use a list if the data must change. - Calling list methods on a tuple.
sizes.append("XL")givesAttributeError: 'tuple' object has no attribute 'append'. Usesizes + ("XL",)or convert withlist(). - Unpacking into the wrong number of names. Two names for three items gives
ValueError: too many values to unpack (expected 2, got 3). Match the count, or use one starred name. - Using two stars.
*best, *worst = scoresgivesSyntaxError: multiple starred expressions in assignment.
Frequently asked questions
What is the difference between a list and a tuple in Python?
A list can be changed after it is created: you can add, remove and replace items. A tuple cannot be changed, so it has only the count() and index() methods. Lists are written with square brackets, tuples with commas and usually round brackets.
How do you create a tuple with one element in Python?
Put a comma after the value: ("Pen",) or just "Pen",. Without the comma, ("Pen") is only the string "Pen" in brackets. Check with type() if you are not sure.
Can a Python function return multiple values?
Yes. return a, b packs the values into one tuple, and the caller can unpack it: low, high = cheapest_and_dearest(prices). Built-in functions such as divmod() work the same way.
Summary
- A tuple is an ordered, immutable collection; the comma makes the tuple, and
()is the empty tuple. - A one-item tuple needs a trailing comma:
("Pen",). - Indexes, slices,
len(),in,count()andindex()work as with lists; changing items does not. a, b, c = tunpacks a tuple; the number of names must match, unless one name has a*to collect the rest as a list.- Swapping (
a, b = b, a), looping over pairs and returning several values all use packing and unpacking.
Next lesson
Next: Lesson 17, Python Dictionary: Keys, Values, get() and Looping with items().
Sources
- Data Structures: Tuples and Sequences (Python tutorial)
- Built-in Types: Tuples (Python docs)
- Simple statements: Assignment statements and starred targets (Python language reference)
- Built-in Functions: divmod() (Python docs)
- Programming FAQ: returning several values as a tuple (Python docs)
- What’s New in Python 3.15: improved error messages (Python docs)
- Python downloads page (python.org)





