Tuples

Reviewed & published by Brayan K

A tuple is an ordered collection like a list — but frozen. Once you create it, it can never change. That sounds restrictive, yet it's exactly what you want for fixed records: a coordinate, an RGB color, a database row, a function returning two values at once.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Tuples also unlock Python's elegant unpacking syntax, which you'll use constantly.

What You'll Learn in This Lesson

1 Creating a Tuple

Tuples use parentheses (or just commas). Once built, they're locked:

point = (3, 4)
rgb = (255, 128, 0)
person = ("Ada", 36, "London")

print(point)              # (3, 4)
print(person[0])          # Ada   (indexing works like a list)

# The commas are what matter — parentheses are optional
also_a_tuple = 1, 2, 3
print(type(also_a_tuple)) # <class 'tuple'>

# An empty tuple
empty = ()
print(len(empty))         # 0
solo = (5)
print(type(solo))    # <class 'int'>   <- NOT a tuple!

solo = (5,)
print(type(solo))    # <class 'tuple'>  <- the comma did it

🔒 Immutability — A Feature, Not a Bug

You can read a tuple freely, but any attempt to change it raises an error. That guarantee is exactly why tuples are useful for fixed data:

coords = (51.5, -0.12)   # latitude, longitude of London

print(coords[0])         # 51.5  — reading is fine

# coords[0] = 52.0       # TypeError: 'tuple' object does not
#                        # support item assignment
# coords.append(1)       # AttributeError: no append on tuples
# Because tuples are hashable, they make great dict keys:
grid = {}
grid[(0, 0)] = "start"
grid[(2, 3)] = "treasure"
print(grid[(2, 3)])      # treasure

# A list as a key would fail:
# grid[[0, 0]] = "x"     # TypeError: unhashable type: 'list'

2 Tuple Unpacking — The Real Superpower

Unpacking spreads a tuple's elements into separate variables in one clean line. You've already seen it in variable swapping — it's everywhere in Python:

point = (3, 4)
x, y = point             # unpack into two variables
print(x, y)              # 3 4

# The famous swap is just unpacking
a, b = 10, 20
a, b = b, a
print(a, b)              # 20 10

# Star captures "the rest" into a list
first, *others = (1, 2, 3, 4, 5)
print(first)             # 1
print(others)            # [2, 3, 4, 5]

# Ignore values you don't need with _
name, _, city = ("Ada", 36, "London")
print(name, city)        # Ada London

3 Returning Multiple Values

This is the single most common professional use of tuples. A function that needs to hand back two or three results just returns them comma-separated — Python packs them into a tuple, and the caller unpacks:

def min_max(numbers):
    return min(numbers), max(numbers)   # returns a tuple

low, high = min_max([4, 9, 2, 7])
print(low, high)          # 2 9

def divide(a, b):
    quotient = a // b
    remainder = a % b
    return quotient, remainder

q, r = divide(17, 5)
print(f"{q} remainder {r}")   # 3 remainder 2

# Built-in functions do this too
print(divmod(17, 5))      # (3, 2) — a tuple!

Looping over pairs uses the same idea — enumerate() and zip() (next lessons) both yield tuples that you unpack right in the for statement.

# A small function returning a rich result as a tuple
def analyze(scores):
    total = sum(scores)
    average = total / len(scores)
    return total, round(average, 1), max(scores)

results = [88, 92, 79, 95, 84]

# Unpack the returned tuple into three variables
total, avg, best = analyze(results)

print(f"Total:   {total}")
print(f"Average: {avg}")
print(f"Best:    {best}")

# You can also keep the whole tuple
summary = analyze(results)
print("Summary tuple:", summary)

# ✅ Expected output:
# Total:   438
# Average: 87.6
# Best:    95
# Summary tuple: (438, 87.6, 95)

🔁 Indexing, Slicing & Looping

Everything you can do to read a list, you can do to a tuple. Only the editing operations are missing:

week = ("Mon", "Tue", "Wed", "Thu", "Fri")

print(week[0])           # Mon
print(week[-1])          # Fri
print(week[1:3])         # ('Tue', 'Wed')   slicing gives a tuple
print(len(week))         # 5
print("Wed" in week)     # True

# Looping is identical to a list
for day in week:
    print(day, end=" ")  # Mon Tue Wed Thu Fri

# The only two tuple methods:
nums = (1, 2, 2, 3, 2)
print(nums.count(2))     # 3  — how many times 2 appears
print(nums.index(3))     # 3  — position of first 3

Tuples have just two methods (count and index) because they can't be modified — there's no append, sort, or remove. To "change" a tuple, convert it: list(my_tuple), edit, then tuple(...) back.

🧩 Reorder Challenge

These lines should compute a midpoint from two coordinate tuples and print it. Reorder them so the output is Midpoint: (3.0, 4.0).

A)   x2, y2 = b
B)   a = (2, 2)
C)   mid = ((x1 + x2) / 2, (y1 + y2) / 2)
D)   x1, y1 = a
E)   b = (4, 6)
F)   print(f"Midpoint: {mid}")

B → E → D → A → C → F

a = (2, 2)                              # B
b = (4, 6)                              # E
x1, y1 = a                              # D -> 2, 2
x2, y2 = b                              # A -> 4, 6
mid = ((x1 + x2) / 2, (y1 + y2) / 2)    # C -> (3.0, 4.0)
print(f"Midpoint: {mid}")               # F

Why: the tuples a (B) and b (E) must exist before you unpack them (D, A). The midpoint calculation (C) needs all four coordinates, and the print (F) comes last.

🧠 Quick Recall

1. What is type(x)?

x = (7)
print(type(x))

<class 'int'> — without a trailing comma, parentheses just group a single value. (7,) would be a tuple.

a, *b = (1, 2, 3, 4)
print(b)

[2, 3, 4] — a takes the first item and the starred b collects the rest into a list.

t = (1, 2, 3)
t[0] = 9
print(t)

TypeError — tuples are immutable, so item assignment raises "'tuple' object does not support item assignment". Nothing prints.

📋 Tuple vs List Quick Reference

FeatureTuple ( )List [ ]
Editable?No (immutable)Yes (mutable)
Syntax(1, 2)[1, 2]
Dict key?Yes (hashable)No
Methodscount, indexappend, sort, ...
Best forFixed recordsChanging data

🎯 Mini Challenge: Coordinate Distance

Use tuple unpacking to compute the distance between two points.

# 🎯 YOUR TURN: distance between two points
p1 = (0, 0)
p2 = (3, 4)

x1, y1 = p1
x2, y2 = p2

distance = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
print(f"Distance from {p1} to {p2}: {distance}")
# Distance from (0, 0) to (3, 4): 5.0

# Bonus: write a function that returns (min, max, range)
def stats(nums):
    return min(nums), max(nums), max(nums) - min(nums)

lo, hi, spread = stats([12, 5, 19, 8])
print(f"low={lo} high={hi} range={spread}")

# ✅ Expected output:
# Distance from (0, 0) to (3, 4): 5.0
# low=5 high=19 range=14

Lesson complete — tuples mastered!

You can create tuples (including the tricky single-item case), use their immutability deliberately, unpack them into variables, and return multiple values from functions. Tuples are the quiet workhorse behind much of Python's clean syntax.

Practice quiz

Which brackets are conventionally used to create a tuple?

  • [ ]
  • { }
  • ( )
  • < >

Answer: ( ). Tuples use parentheses, e.g. (3, 4), though the commas are what truly create them.

What is type((5))?

  • int
  • tuple
  • list
  • set

Answer: int. Without a trailing comma, (5) is just the integer 5 in parentheses.

How do you create a single-item tuple containing 5?

  • (5)
  • [5]
  • {5}
  • (5,)

Answer: (5,). A one-element tuple needs a trailing comma: (5,).

What makes a tuple different from a list?

  • Tuples are unordered
  • Tuples are immutable (cannot be changed)
  • Tuples can't hold strings
  • Tuples can't be looped

Answer: Tuples are immutable (cannot be changed). Tuples are immutable: once created their elements cannot change.

What does t[0] = 9 do for a tuple t = (1, 2, 3)?

  • Raises a TypeError
  • Changes the first item to 9
  • Returns 9
  • Adds 9 to the tuple

Answer: Raises a TypeError. Item assignment on a tuple raises a TypeError because tuples are immutable.

After first, *others = (1, 2, 3, 4, 5), what is others?

  • 1
  • (2, 3, 4, 5)
  • [2, 3, 4, 5]
  • 5

Answer: [2, 3, 4, 5]. The starred variable collects the remaining items into a list: [2, 3, 4, 5].

Why can a tuple be used as a dictionary key but a list cannot?

  • Tuples are shorter
  • Tuples are hashable (immutable)
  • Lists are too slow
  • Tuples are ordered

Answer: Tuples are hashable (immutable). Tuples are hashable because they're immutable, so they can be dict keys or set members.

Which two methods do tuples have?

  • append and sort
  • add and remove
  • push and pop
  • count and index

Answer: count and index. Tuples only have count and index because they can't be modified.

What does divmod(17, 5) return?

  • 3.4
  • (3, 2)
  • [3, 2]
  • 2

Answer: (3, 2). divmod returns a tuple of the quotient and remainder: (3, 2).

A function with 'return min(nums), max(nums)' returns what kind of object?

  • A list
  • Two separate values
  • A tuple
  • A dictionary

Answer: A tuple. Comma-separated return values are packed into a single tuple.

Continue this course

Frequently asked questions

What's the difference between a tuple and a list?

Both store an ordered sequence of items, but a tuple is immutable — once created you cannot add, remove, or change its elements. Lists use square brackets and are editable; tuples use parentheses and are fixed. Use a tuple when the collection represents a single, unchanging record like a coordinate or an RGB color.

Do I actually need the parentheses to make a tuple?

Often not. It's the commas that create a tuple, so x = 1, 2, 3 is a valid tuple. Parentheses just make it clearer and are required in some contexts. The one place they matter most: a single-item tuple needs a trailing comma, like (5,) — without it, (5) is just the number 5.

Why would I use an immutable tuple instead of a flexible list?

Immutability is a feature, not a limitation. It signals 'this data shouldn't change', protects against accidental edits, makes tuples hashable so they can be dictionary keys or set members, and lets Python store them slightly more efficiently. They're perfect for fixed records returned from functions.

What is tuple unpacking?

Unpacking assigns each element of a tuple to its own variable in one line: x, y = (3, 4). It's the mechanism behind swapping (a, b = b, a), looping over pairs, and returning multiple values from a function. The star operator (a, *rest = ...) captures the remaining items into a list.

Can a function return more than one value?

Yes — a function returns a single object, but that object is commonly a tuple, which looks like returning several values. return name, score builds a tuple, and the caller unpacks it with n, s = get_player(). This is one of the most common real-world uses of tuples in Python.