Python Tuples: Immutable Sequences with Examples - Python with AI tutorial chapter 14
Python

Python Tuples: Immutable Sequences with Examples

Python with AI Tutorial · Chapter 14 of 48

Python tuples are ordered collections that cannot be changed after they are created, written in parentheses such as ("Pune", 411001, "India"). They hold records whose shape is fixed: a coordinate pair, a database row, the two values a function hands back. This chapter covers creating Python tuples, unpacking them, the few methods they have and when to choose them over lists.

Creating and accessing a tuple

Write the items between parentheses. Indexing, negative indexing, slicing and len() work exactly as they do for lists and strings, because a tuple is a sequence too.

office = ("Pune", 411001, "India")

print(office)
print(office[0])
print(office[-1])
print(len(office))
print(type(office))
Output:
('Pune', 411001, 'India')
Pune
India
3
<class 'tuple'>

The one-item tuple and optional parentheses

It is the comma, not the parentheses, that makes a tuple. A single value in brackets is just that value, so a one-item tuple needs a trailing comma. Going the other way, several values separated by commas form a tuple even without brackets, which is what you see in return a, b and in swap statements.

single = ("Finance",)
not_a_tuple = ("Finance")
coords = 18.52, 73.86

print(type(single), type(not_a_tuple), type(coords))
print(len(single))
Output:
<class 'tuple'> <class 'str'> <class 'tuple'>
1

Tuples are immutable

You cannot assign to an index, append, remove or sort a tuple in place. To “change” one you build a new tuple and rebind the name. This is a feature: a tuple is a promise that the record will not be altered by accident somewhere else in the program.

quarter = ("Q1", 125000)
# quarter[1] = 130000   # TypeError: 'tuple' object does not support item assignment

quarter = ("Q1", 130000)
print(quarter)
Output:
('Q1', 130000)
Watch out: immutability is shallow. A tuple that contains a list cannot swap the list for something else, but the list itself can still be modified: with t = (1, [2, 3]), calling t[1].append(4) works and t becomes (1, [2, 3, 4]). For a truly frozen record, keep only immutable items inside the tuple.

Unpacking

Unpacking assigns each item of a tuple to its own variable in one statement. The number of names must match the number of items, unless you use a starred name to soak up the remainder. Swapping two variables is the classic one-liner that relies on tuple packing and unpacking together.

employee = ("Anita Desai", "Finance", 61000)
name, dept, salary = employee
print(name)
print(f"{dept}: {salary:,}")

first, *rest = (2026, 9, 5, 14, 30)
print(first, rest)

a, b = 10, 20
a, b = b, a
print(a, b)
Output:
Anita Desai
Finance: 61,000
2026 [9, 5, 14, 30]
20 10

The starred name always collects into a list, even when the source is a tuple. Unpacking also works on lists and strings, but it is most common with tuples because their fixed length makes the pattern safe.

Try it with AI

Ask the assistant to explain unpacking edge cases and to show what error each wrong pattern produces.

Explain Python tuple unpacking with these five examples and show the exact output or error message for each on Python 3.12: (1) a, b = (1, 2, 3); (2) a, *b, c = (1, 2, 3, 4, 5); (3) (a, b), c = (1, 2), 3; (4) for k, v in [("x", 1), ("y", 2)]: print(k, v); (5) a, = (7,). Then give me three realistic business examples where unpacking makes code clearer than indexing.

Tuple methods and built-in functions

Because they cannot change, tuples have only two methods: count() and index(). Everything else comes from the general-purpose built-ins that work on any sequence.

ratings = (4, 5, 3, 5, 4, 5)

print(ratings.count(5))
print(ratings.index(3))
print(max(ratings), min(ratings), sum(ratings))
print(sorted(ratings))
print(5 in ratings)
Output:
3
2
5 3 26
[3, 4, 4, 5, 5, 5]
True

Note that sorted() returns a list, not a tuple. Wrap it in tuple() if you need the immutable type back.

Slicing, joining and repeating

Slices, + and * all return new tuples, so they are allowed even though the originals never change.

months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun")

print(months[:3])
print(months[3:] + ("Jul",))
print(("-",) * 3)
Output:
('Jan', 'Feb', 'Mar')
('Apr', 'May', 'Jun', 'Jul')
('-', '-', '-')

Tuples from functions and in loops

Returning several values from a function really returns one tuple, and the caller usually unpacks it immediately. Lists of tuples are the standard way to hold simple records, and enumerate() hands you a tuple of index and item.

def min_max(values):
    return min(values), max(values)

low, high = min_max([1200, 980, 1500, 430])
print(low, high)

orders = [("ORD-1", 1250.0), ("ORD-2", 830.5), ("ORD-3", 2100.0)]
for order_id, amount in orders:
    print(order_id, amount)

for i, (order_id, amount) in enumerate(orders, start=1):
    print(i, order_id)
Output:
430 1500
ORD-1 1250.0
ORD-2 830.5
ORD-3 2100.0
1 ORD-1
2 ORD-2
3 ORD-3

Tuples as dictionary keys and type conversion

Because tuples are hashable when their contents are, they can serve as dictionary keys and set members, which lists cannot. That makes them ideal for compound keys such as region plus year. When you do need to edit the contents, convert to a list, change it and convert back.

sales = {("North", 2025): 410000, ("North", 2026): 455000}
print(sales[("North", 2026)])

items = list(("a", "b"))
items.append("c")
print(tuple(items))
Output:
455000
('a', 'b', 'c')

Named tuples

A plain tuple forces you to remember that position 2 is the salary. namedtuple from the collections module gives each position a name while keeping the tuple’s immutability and low memory use, and it prints itself readably.

from collections import namedtuple

Employee = namedtuple("Employee", ["name", "dept", "salary"])
e = Employee("Rahul Verma", "Sales", 48000)

print(e.name, e.salary)
print(e)
Output:
Rahul Verma 48000
Employee(name='Rahul Verma', dept='Sales', salary=48000)

Tuple vs list

Feature Tuple List
Syntax (1, 2, 3) or 1, 2, 3 [1, 2, 3]
Mutable No Yes
Methods count, index Eleven, including append, sort, pop
Usable as dict key or set member Yes (if contents are hashable) No
Typical meaning One record with fixed fields A collection of similar items that grows and shrinks
Memory and speed Slightly smaller and faster to create Slightly larger

A useful rule of thumb: if the position of each value has a meaning (name, department, salary), use a tuple; if every item is the same kind of thing (a list of salaries), use a list.

Try it with AI

Show the assistant a piece of your own code that uses lists for fixed records and ask whether tuples or named tuples would be safer.

Here is Python code that stores employee records as lists: rows = [["Anita", "Finance", 61000], ["Rahul", "Sales", 48000]]. Rewrite it three ways: with plain tuples, with collections.namedtuple, and with a typing.NamedTuple class that has type hints. For each version, show how to read the salary of the second employee and how to give Rahul a 5% raise. Then tell me which version you recommend for a small reporting script and why, in three sentences.

Common mistakes

  • Writing ("Finance") and expecting a tuple. Without the comma it is a string.
  • Trying to append() to or assign into a tuple, which raises AttributeError or TypeError.
  • Unpacking into the wrong number of names, which raises ValueError: too many values to unpack.
  • Using a tuple that contains a list as a dictionary key, which fails with TypeError: unhashable type.
  • Choosing a tuple for a collection that clearly needs to grow, then converting back and forth to a list repeatedly.

Exercise

An order is a list of tuples (product, quantity, unit_price): [("Laptop", 2, 899.0), ("Monitor", 3, 250.0), ("Mouse", 10, 25.0)]. Build a list of (product, line_total) tuples using unpacking in a comprehension, print it, then unpack the largest line into two variables and print a sentence about it.

Show answer
lines = [("Laptop", 2, 899.0), ("Monitor", 3, 250.0), ("Mouse", 10, 25.0)]

totals = [(name, qty * price) for name, qty, price in lines]
print(totals)

best_name, best_total = max(totals, key=lambda t: t[1])
print(f"Largest line: {best_name} at {best_total:,.2f}")
Output:
[('Laptop', 1798.0), ('Monitor', 750.0), ('Mouse', 250.0)]
Largest line: Laptop at 1,798.00

The comprehension unpacks each three-item tuple as it goes, and max() with a key function returns the whole winning tuple, which is then unpacked again.

Related chapters

FAQ

When should I use a tuple instead of a list?

Use a tuple for a fixed record where each position has its own meaning, for values returned from a function, and for anything that must serve as a dictionary key. Use a list when the collection will grow, shrink or be sorted.

Can a tuple be changed in Python?

No. Tuples are immutable, so you cannot assign to an index, append or remove items. You can create a new tuple from the old one, and mutable objects stored inside a tuple, such as lists, can still be changed.

How do I create a tuple with one item?

Add a trailing comma: (“Finance”,) or simply “Finance”,. Writing (“Finance”) without the comma gives a plain string, because parentheses alone do not create a tuple.

Working with spreadsheets too? Ready-made Excel, Google Sheets and Power BI templates are at NextGenTemplates.com.

Chapter 14 of 48 · Python with AI: all 48 chapters

PK
Meet PK, the founder of NeotechNavigators.com! With over 15 years of experience in Data Visualization, Excel Automation, and dashboard creation. PK is a Microsoft Certified Professional who has a passion for all things in Excel. PK loves to explore new and innovative ways to use Excel and is always eager to share his knowledge with others. With an eye for detail and a commitment to excellence, PK has become a go-to expert in the world of Excel. Whether you're looking to create stunning visualizations or streamline your workflow with automation, PK has the skills and expertise to help you succeed. Join the many satisfied clients who have benefited from PK's services and see how he can take your data analysis skills to the next level!
https://neotechnavigators.com