Python - Tuples

Overview

Estimated time: 15–25 minutes

Use tuples as immutable, ordered collections. Learn packing/unpacking and when tuples are preferred to lists.

Learning Objectives

  • Create tuples and use tuple unpacking.
  • Understand immutability and hashing implications.
  • Use tuples as lightweight records and multiple return values.

Prerequisites

Basics and unpacking

t = (1, 2, 3)
a, b, c = t
print(a, c)

# packing without parentheses
a_pair = 10, 20
print(a_pair)

Tuples as keys

coords = {(0, 0): "origin", (1, 2): "A"}
print(coords[(1, 2)])

Common Pitfalls

  • Single-element tuple needs a trailing comma: (42,).
  • Trying to modify a tuple: convert to a list, modify, then convert back if needed.

Checks for Understanding

  1. How do you create a 1-element tuple?
  2. Why can tuples be used as dict keys but lists cannot?
Show answers
  1. (value,) with a trailing comma.
  2. Tuples are immutable and hashable; lists are mutable and unhashable.

Exercises

  1. Return multiple values from a function using a tuple and unpack them at the call site.
  2. Build a dict keyed by coordinate tuples and query it.