Tutorials Python Python Tuples
Ch 20 / 58
Python Beginner 10 min read Chapter 20 of 58

Python Tuples

A tuple is Python's immutable ordered sequence — like a list that can never be changed after creation. Tuples are faster, safer, and can be used as dictionary keys. This chapter covers everything: creating tuples (including the single-element trap), indexing with a visual diagram, slicing, the powerful tuple unpacking and starred assignment, built-in methods, named tuples, and a definitive tuple vs list comparison so you always know which to choose.

What you'll learn in this chapter
Creating tuples and the single-element comma trap
Indexing (positive & negative) with index diagram
Immutability — what it means and why it matters
Tuple unpacking & starred assignment
Named tuples for readable data records
Tuple vs list — when to use each
Advertisement

Creating Tuples

A tuple is an ordered, immutable sequence enclosed in parentheses (). Elements are separated by commas. The parentheses are actually optional — it is the commas that make a tuple, not the brackets. Tuples can hold any mix of data types.

Single-element tuple — trailing comma required! (42) is just an integer inside parentheses. To create a one-element tuple you must add a trailing comma: (42,). This is the most common beginner mistake with tuples.
Ordered
Items keep their positions
Immutable
Cannot change after creation
Duplicates OK
Same value can repeat
Hashable
Can be used as dict key
Python — creating_tuples.py
# Empty tuple
empty   = ()
empty2  = tuple()

# Tuple of integers
coords  = (10, 20, 30)

# Parentheses are OPTIONAL — commas make the tuple!
rgb     = 255, 128, 0           # valid tuple without ()
print(type(rgb))                  # <class 'tuple'>

# ⚠️ Single-element trap — MUST have trailing comma
not_a_tuple = (42)    # just an int — no comma
is_a_tuple  = (42,)   # ← trailing comma makes it a tuple
also_tuple  = 42,      # also valid
print(type(not_a_tuple))  # <class 'int'>
print(type(is_a_tuple))   # <class 'tuple'>

# Mixed types
person  = ("Alice", 25, "Vadodara", True)

# Tuple from iterables
chars   = tuple("Python")       # ('P','y','t','h','o','n')
nums    = tuple(range(1, 6))   # (1, 2, 3, 4, 5)

# Built-in functions on tuples
print(len(person))    # 4
print(min(coords))    # 10
print(max(coords))    # 30
print(sum(coords))    # 60

Indexing & Slicing

Tuple indexing and slicing work identically to lists. Zero-based positive indices access from the start; negative indices access from the end. Slicing always returns a new tuple — the original remains unchanged (it couldn't be changed anyway).

Index positions — point = ("a", "b", "c", "d", "e")
Positive index (left → right) Negative index (right → left)
0
1
2
3
4
"a"
"b"
"c"
"d"
"e"
-5
-4
-3
-2
-1
Python — tuple_index_slice.py
point = ("a", "b", "c", "d", "e")

# Positive indexing (zero-based)
print(point[0])      # a  — first element
print(point[2])      # c
print(point[4])      # e  — last element

# Negative indexing (right to left)
print(point[-1])     # e  — last
print(point[-3])     # c
print(point[-5])     # a  — first

# Slicing — returns new tuple
print(point[1:4])    # ('b', 'c', 'd')
print(point[:3])     # ('a', 'b', 'c')
print(point[2:])     # ('c', 'd', 'e')
print(point[::2])    # ('a', 'c', 'e')  — every other
print(point[::-1])   # ('e', 'd', 'c', 'b', 'a')  — reversed

# Membership test
print("c" in point)      # True
print("z" not in point)  # True

# Iterate over tuple
for v in point:
    print(v, end=" ")  # a b c d e

Immutability — Tuples Cannot be Changed

Once created, a tuple's elements cannot be added, removed, or replaced. Any attempt raises a TypeError. However, if a tuple contains a mutable object (like a list), that inner object can still be modified — only the tuple's references are fixed.

Python — tuple_immutability.py
t = (1, 2, 3)

# ❌ ALL of these raise TypeError / AttributeError
# t[0] = 99    → TypeError: 'tuple' object does not support item assignment
# t.append(4)  → AttributeError: 'tuple' has no attribute 'append'
# del t[0]     → TypeError: 'tuple' object doesn't support item deletion

# ✅ Tuple containing a mutable list — inner list CAN change
mixed = (1, [2, 3], 4)
mixed[1].append(99)   # the LIST changes; tuple refs are unchanged
print(mixed)            # (1, [2, 3, 99], 4)

# "Modify" a tuple by creating a NEW one
t = t + (4, 5)          # creates NEW tuple and rebinds t
print(t)                # (1, 2, 3, 4, 5)

t2 = t[:2] + (99,) + t[2:]  # "insert" 99 at index 2
print(t2)               # (1, 2, 99, 3, 4, 5)

# Tuples are HASHABLE → can be dict keys and set members
locations = {(0,0): "origin", (1,0): "right"}
print(locations[(0,0)])  # origin

# Lists are NOT hashable — this would fail:
# {[0,0]: "origin"}  →  TypeError: unhashable type: 'list'
Why immutability is a feature Immutable objects are thread-safe, hashable (usable as dict keys), and slightly faster to iterate. Use tuples when the data represents a fixed record that must never change — coordinates, RGB values, database rows, function return values.
Advertisement
K2infocom Python Masterclass & Backend Development
Master Python, Django & Backend APIs with AI
Go from absolute beginner to building production-ready REST APIs, web applications, and ML pipelines. Real projects, live mentoring in Vadodara, and placement support included.
2,400+
Students Enrolled
4.9 ⭐
Google Rating
6 Months
Full Program
100%
Placement Support
Python 3 Django & DRF FastAPI PostgreSQL Machine Learning Docker & AWS Real Projects AI Tools

Tuple Unpacking & Starred Assignment

Tuple unpacking assigns each element of a tuple to a separate variable in one statement. The starred assignment (*) captures multiple remaining elements into a list. These features make Python code remarkably concise and readable.

Python — tuple_unpacking.py
# Basic unpacking — left side must match count on right
point = (10, 20, 30)
x, y, z = point
print(x, y, z)         # 10 20 30

# Variable swap — most Pythonic way (no temp variable!)
a, b = 5, 10
a, b = b, a
print(a, b)            # 10 5

# Unpack function return value
def min_max(nums):
    return min(nums), max(nums)  # returns tuple

lo, hi = min_max([5, 1, 9, 3])
print(lo, hi)          # 1 9

# Discard values with _ (convention)
name, _, city = ("Alice", 25, "Vadodara")
print(name, city)      # Alice Vadodara

# Starred assignment — capture multiple into list
first, *rest = (1, 2, 3, 4, 5)
print(first, rest)     # 1  [2, 3, 4, 5]

*head, last = (1, 2, 3, 4, 5)
print(head, last)      # [1, 2, 3, 4]  5

a, *mid, b = (1, 2, 3, 4, 5)
print(a, mid, b)       # 1  [2, 3, 4]  5

# Nested unpacking in for loop
students = [("Alice", 90), ("Bob", 85), ("Carol", 92)]
for name, score in students:
    print(f"{name}: {score}")
a, b = b, a
Python evaluates the right side as a tuple (b, a) first (capturing current values), then unpacks — so no temporary variable is needed.
first, *rest = t
Starred assignment collects all unmatched elements into a list. Only one star per unpacking; it can be in any position — first, last, or middle.
_ as discard
Using _ signals "I don't need this value" — a convention that prevents unused-variable warnings and improves readability.

Tuple Methods

Because tuples are immutable, they have only two built-in methods: count() and index(). All the modifying methods from lists — append, sort, remove, etc. — are unavailable. Standard built-in functions (len, min, max, sorted, reversed) still work on tuples.

Python — tuple_methods.py
scores = (85, 92, 78, 92, 85, 90)

# count(x) — number of occurrences
print(scores.count(92))   # 2
print(scores.count(85))   # 2
print(scores.count(99))   # 0 — not present

# index(x) — index of FIRST occurrence (ValueError if absent)
print(scores.index(92))   # 1
print(scores.index(90))   # 5
# scores.index(99)  → ValueError: tuple.index(x): x not in tuple

# Standard built-in functions (all work on tuples)
print(len(scores))         # 6
print(min(scores))         # 78
print(max(scores))         # 92
print(sum(scores))         # 522

# sorted() → returns a NEW LIST (not tuple!)
print(sorted(scores))      # [78, 85, 85, 90, 92, 92]

# reversed() → returns an iterator; wrap in tuple()
print(tuple(reversed(scores)))
# (90, 85, 92, 78, 92, 85)

# Concatenation and repetition — create NEW tuples
print((1,2) + (3,4))      # (1, 2, 3, 4)
print((0,) * 4)           # (0, 0, 0, 0)

Named Tuples

A named tuple is a subclass of tuple that gives each position a meaningful name. Code that reads person.name is far clearer than person[0]. Named tuples are a lightweight alternative to classes for storing immutable records — no boilerplate required.

Python — named_tuples.py
from collections import namedtuple

# Define a named tuple class
Point = namedtuple("Point", ["x", "y", "z"])
p     = Point(1, 2, 3)

# Access by name — clear and readable
print(p.x, p.y, p.z)  # 1 2 3

# Also accessible by index (still a real tuple)
print(p[0], p[1])    # 1 2
print(isinstance(p, tuple))  # True

# _replace() — return modified copy (original unchanged)
p2 = p._replace(z=99)
print(p2)               # Point(x=1, y=2, z=99)
print(p)                # Point(x=1, y=2, z=3) ← unchanged

# Useful attributes
print(p._fields)        # ('x', 'y', 'z')
print(p._asdict())      # {'x': 1, 'y': 2, 'z': 3}

# Practical: database row representation
Employee = namedtuple("Employee", ["name", "dept", "salary"])
emp = Employee("Alice", "Engineering", 95000)
print(f"{emp.name} in {emp.dept}: ₹{emp.salary}")
# Alice in Engineering: ₹95000

# Modern style — typing.NamedTuple (Python 3.6+)
from typing import NamedTuple

class Color(NamedTuple):
    red:   int
    green: int
    blue:  int = 0   # default value

c = Color(255, 128)
print(c)               # Color(red=255, green=128, blue=0)
print(c.red, c.blue)   # 255 0
When to use typing.NamedTuple vs namedtuple Prefer class MyRecord(NamedTuple): for new code — it supports type annotations, default values, and works with IDE auto-complete. Use collections.namedtuple for quick, script-level record types.

Tuple vs List — Side-by-Side Comparison

Choosing between a tuple and a list communicates intent: use a list for a collection that may grow or change; use a tuple for a fixed record that represents one logical entity.

Tuple
List
Immutable — cannot be changed
Mutable — can be changed
Defined with () or just commas
Defined with []
Hashable — can be dict key or set item
Not hashable — cannot be dict key
Only 2 methods: count(), index()
11 methods: append, sort, remove…
Faster iteration, less memory
Slightly more overhead
Best for fixed records (coords, RGB, rows…)
Best for dynamic growing collections
Python — tuple_vs_list.py
# ✅ Use TUPLE — fixed records
coordinate = (10.5, 20.3)
rgb        = (255, 128, 0)
date       = (2025, 5, 12)
db_row     = (1, "Alice", "Engineer")
quotient   = divmod(17, 5)    # (3, 2) — Python returns tuples

# ✅ Use LIST — dynamic, grows and shrinks
cart   = ["apple", "bread"]
cart.append("milk")
cart.remove("bread")

# Tuple as dict key — hashable!
board = {
    (0,0): ".", (0,1): "X",
    (1,0): "O", (1,1): "."
}
print(board[(0,1)])      # X

# Convert between them
t   = (1, 2, 3)
lst = list(t)    # tuple → list  [1, 2, 3]
t2  = tuple(lst) # list → tuple  (1, 2, 3)

Practice Python Online — Free Compilers

Don't want to install anything yet? Practice all tuple examples from this chapter directly in your browser with these free Python environments.

▶
Online Python 3 Compiler
Write, run and debug Python code in your browser. No installation required. Test every tuple example instantly.
Open Compiler
Replit
Full IDE online
Google Colab
Free GPU notebooks
JupyterLite
Notebooks in browser
Programiz
Beginner-friendly
Chapter Summary
  • A tuple is an ordered, immutable sequence. It is the comma — not the parentheses — that creates a tuple.
  • A single-element tuple requires a trailing comma: (42,). Without it, (42) is just an integer.
  • Indexing starts at 0; negative indices count from the end. Slicing returns a new tuple and uses the same [start:stop:step] syntax as lists.
  • Tuples are immutable — elements cannot be added, changed, or removed. Mutable objects inside a tuple can still be mutated.
  • Tuple unpacking: x, y, z = (1, 2, 3). Use a, b = b, a for the Pythonic variable swap with no temp variable.
  • Starred assignment: first, *rest = t — captures remaining elements into a list. Only one star per expression.
  • Tuples have only two methods: count() and index(). Standard functions len(), min(), max(), sorted() all work on tuples.
  • Named tuples give fields readable names. Use collections.namedtuple or the modern typing.NamedTuple class syntax.
  • Use tuple for fixed records (coordinates, return values, dict keys). Use list for dynamic, growing collections.
⚡
Free Resource
Download our Python Tuples Cheat Sheet
Tuple creation, indexing, unpacking, named tuples & tuple vs list guide — one printable page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

You must add a trailing comma after the element. The comma — not the parentheses — is what defines a tuple. Without the trailing comma, Python treats the expression in parentheses as just the value itself (grouping, not tuple creation).

not_a_tuple = (42)    # int — just grouping with ()
is_a_tuple  = (42,)   # ← trailing comma = tuple
also_tuple  = 42,      # also valid without ()
print(type(is_a_tuple))  # <class 'tuple'>
✓ Answer

Tuple unpacking assigns each element of a tuple (or any iterable) to separate variables in one statement, matched by position. The number of variables on the left must equal the number of elements on the right (unless using starred assignment).

For the variable swap, Python evaluates the right side as a tuple (b, a) first — capturing current values — then unpacks it. No temporary variable needed:

a, b = 5, 10
a, b = b, a   # Pythonic swap
print(a, b)   # 10 5
✓ Answer

Dictionary keys must be hashable — Python computes a hash value for each key to find it in the hash table. For a hash to be reliable, the object must be immutable (its value never changes).

Tuples are immutable — their hash is constant. Lists are mutable — if a list were used as a key and then modified, its hash would change, breaking the dictionary. Python raises TypeError: unhashable type: 'list' when you try.

# ✅ Tuple as dict key
d = {(0,0): "origin"}

# ❌ List as dict key → TypeError
# d = {[0,0]: "origin"}
✓ Answer

A starred variable (*name) in an unpacking expression captures all remaining elements that aren't matched to other variables. The collected elements are always stored as a list. Only one starred variable is allowed per unpacking, but it can be in any position — first, last, or middle:

first, *rest = (1,2,3,4)  # rest=[2,3,4]
*init, last = (1,2,3,4)  # init=[1,2,3]
a, *mid, z  = (1,2,3,4)  # mid=[2,3]
✓ Answer

A named tuple is a subclass of tuple that assigns a name to each position. It eliminates "magic number" indexing — person.name is far clearer than person[0]. Named tuples have all tuple behaviours (immutable, hashable, iterable) plus named field access.

Use named tuples when:

  • You have a fixed-structure record and want readable field names
  • You want a lightweight alternative to a full class (no boilerplate)
  • The data must remain immutable and hashable (unlike a dict)
MCQ 1 of 3
What is the output of type((42)) in Python?
MCQ 2 of 3
What is the output of: a, *b, c = (1, 2, 3, 4, 5) — what is b?
MCQ 3 of 3
Which of the following is the correct way to create an empty tuple?

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel