Tuples In Python — PBA Institute Tutorial
Chapter 14 · Python Programming Series
12 min read Beginner

Immutable Sequences With Tuples

A tuple is Python's immutable cousin of the list. Once created, it can never be changed — and that constraint makes tuples faster, hashable, and safer for storing fixed records like coordinates, RGB values, or database rows. This chapter shows you everything tuples can do and where they shine.

Overview

🔒

Immutable

Locked once created — perfect for fixed records.

Faster

Slightly faster than lists due to fixed size and reduced overhead.

🔑

Hashable

Use as dict keys or set members (when elements are hashable).

📦

Multi-Return

Returning a tuple is Python's elegant multi-value return.

🏷️

Named Tuples

Add field names without the overhead of a full class.

Syntax

  • Create with () or tuple(): point = (3, 4).
  • A single-element tuple needs a trailing comma: (5,).
  • Access elements with indices, just like lists: point[0].
  • Tuples cannot be modified — methods are limited to count() and index().
Tuples — Syntax
# create
empty = ()
single = (5,)
point = (3, 4)
rgb = (255, 128, 0)

# unpack
x, y = point
r, g, b = rgb
print(f"x={x}, y={y}")

# tuple as dict key
locations = {(0, 0): "origin", (1, 1): "diagonal"}

Detailed Explanation

  • Immutability: Once created, a tuple cannot be changed — no append, no delete, no item assignment. This makes tuples safer and slightly faster.
  • Packing and unpacking: Packing: t = 1, 2, 3. Unpacking: a, b, c = t. Extended unpacking: head, *rest = (1, 2, 3, 4).
  • Single-element tuples: (5) is just the integer 5; (5,) is a one-element tuple. Always include the comma.
  • Tuples as keys: Because tuples are hashable (if all their elements are), you can use them as keys in dictionaries or members of sets.
  • Named tuples: collections.namedtuple creates lightweight class-like tuples with named fields: Point = namedtuple('Point', 'x y').
  • When to choose tuples: Use tuples for fixed records, multi-return values, dictionary keys, and when immutability is a feature.

Code Examples

Example 1 — Create & Access
point = (3, 4)
print(point[0])
print(point[1])
Output 3
4
Example 2 — Unpacking
name, age, city = ("Riya", 22, "Mumbai")
print(name, age, city)
Output Riya 22 Mumbai
Example 3 — Extended Unpacking
head, *body, tail = (10, 20, 30, 40, 50)
print(head, body, tail)
Output 10 [20, 30, 40] 50
Example 4 — Tuple as Dictionary Key
distances = {("A","B"): 5, ("B","C"): 3, ("A","C"): 7}
print(distances[("A","C")])
Output 7
Example 5 — Multi-Return from Function
def min_max(nums):
    return min(nums), max(nums)

lo, hi = min_max([4, 8, 1, 9, 3])
print("lo =", lo, "hi =", hi)
Output lo = 1 hi = 9
Example 6 — Named Tuple
from collections import namedtuple
Point = namedtuple("Point", "x y")
p = Point(3, 4)
print(p.x, p.y)
print(p)
Output 3 4
Point(x=3, y=4)

Real-World Use Cases

Coordinates

(latitude, longitude) stays fixed for a location.

RGB Colours

Three-tuple of red, green, blue intensities.

DB Rows

Each fetched record is naturally a tuple.

Function Returns

Return more than one value cleanly without classes.

Composite Keys

Use tuples as keys for caches and lookup tables.

Read-Only Config

Group constants that should never be mutated.

Notes & Pro Tips

  • Tuples are immutable — but they can contain mutable objects like lists.
  • Use named tuples when readability matters: p.x is clearer than p[0].
  • Tuples literals don't require brackets — but using them improves readability.
  • Convert with list(t) when you need mutability.
  • tuple() with no args creates an empty tuple — the only zero-element tuple.
  • Use tuples for fixed-length structures; use lists for collections that may grow or shrink.

Common Mistakes

  • Missing trailing comma: (5) is an integer, not a tuple.
  • Trying to modify: t[0] = 99 raises TypeError.
  • Using a list as a dict key: use a tuple instead — lists aren't hashable.
  • Mistaking tuple for list: tuples lack append/remove/sort methods.
  • Forgetting unpacking count: too few or too many names raises ValueError.
  • Mutable elements inside a tuple: the tuple is immutable but nested lists still change.

Practice Problems

  • Problem 1: Create a tuple of 10 numbers and print the maximum, minimum and sum.
  • Problem 2: Swap two variables using tuple packing/unpacking in one line.
  • Problem 3: Convert a list of (name, marks) tuples into a dictionary.
  • Problem 4: Write a function that returns (quotient, remainder) using divmod.
  • Problem 5: Create a namedtuple Student with fields name, age, marks and print one record.
  • Problem 6: Given a list of (x, y) tuples, print the centroid (average x and y).

Interview Questions

  • Q1. What is the difference between a list and a tuple?
  • Q2. Why are tuples faster than lists in Python?
  • Q3. Can a tuple contain mutable elements? What does that imply?
  • Q4. What is a namedtuple and when would you use one?
  • Q5. Why is (5) not a tuple but (5,) is?
  • Q6. When would you use a tuple as a dictionary key?

Frequently Asked Questions

  • Q1: What's the difference between a list and a tuple?
    Lists are mutable and use []; tuples are immutable and use (). Tuples are slightly faster and hashable.
  • Q2: How do I create an empty tuple?
    Use () or tuple(). For a one-element tuple, you must use a trailing comma: (5,).
  • Q3: Can I modify a tuple?
    No — assignment to a tuple element raises TypeError. You can only create a new tuple.
  • Q4: Why use tuples as dict keys?
    Tuples are hashable, so they can serve as composite keys in dictionaries or members of sets.
  • Q5: What is tuple unpacking?
    Assigning multiple variables from a tuple at once: a, b, c = (1, 2, 3). Use *rest to capture multiple.
  • Q6: Is namedtuple better than a class?
    For simple immutable records — yes. It is lightweight and has built-in equality and printing.

Summary

Tuples are the immutable, slightly-faster cousins of lists. Use them whenever you have a fixed-shape record, a multi-return value, or need a hashable composite key. Combined with Python's powerful unpacking syntax and the optional named-tuple style, they make your code more expressive, safer, and often faster — all with very little extra effort.

Continue Learning

Previous

Go to Previous Chapter

Next

Go to Next Chapter