Ad – 728Γ—90
πŸ“¦ Data Structures

Python Tuples – Immutable Sequences with Examples

A tuple is an ordered, immutable sequence of elements. Like a list, but once created, you cannot add, remove, or change its elements. Tuples are faster than lists, can be used as dictionary keys, and signal to other developers that this data should not be modified.

⏱️ 18 min read 🎯 Beginner πŸ“… Updated 2026

Creating Tuples

Tuples use parentheses (optional but recommended). A single-element tuple requires a trailing comma.

Python
# Creating tuples
t1 = (1, 2, 3)
t2 = "a", "b", "c"    # Parentheses optional
t3 = (42,)             # Single element - MUST have comma!
t4 = ()                # Empty tuple

print(t1)   # (1, 2, 3)
print(t2)   # ('a', 'b', 'c')
print(t3)   # (42,)
print(type(t4))  # 
β–Ά Output
(1, 2, 3) ('a', 'b', 'c') (42,)

Accessing Tuple Elements

Same indexing and slicing as lists.

Python
coords = (10, 20, 30)

print(coords[0])    # 10  - first element
print(coords[-1])   # 30  - last element
print(coords[1:])   # (20, 30) - slice

# But you CANNOT modify:
try:
    coords[0] = 99
except TypeError as e:
    print(f"Error: {e}")
β–Ά Output
10 30 (20, 30) Error: 'tuple' object does not support item assignment
Ad – 336Γ—280

Tuple Unpacking

Assign tuple elements to individual variables β€” a very Pythonic pattern.

Python
# Basic unpacking
point = (4, 7)
x, y = point
print(f"x={x}, y={y}")

# Swap variables (uses tuple packing/unpacking)
a, b = 10, 20
a, b = b, a
print(f"a={a}, b={b}")  # a=20, b=10

# Extended unpacking with *
first, *rest = (1, 2, 3, 4, 5)
print(first)   # 1
print(rest)    # [2, 3, 4, 5]
β–Ά Output
x=4, y=7 a=20, b=10 1 [2, 3, 4, 5]

When to Use Tuples vs Lists

Use a tuple when data should not change. Use a list when you need to modify the collection.

Python
# βœ… Tuples for fixed data
RGB_RED = (255, 0, 0)
DAYS_OF_WEEK = ("Mon","Tue","Wed","Thu","Fri","Sat","Sun")
DATABASE_CONFIG = ("localhost", 5432, "mydb")

# βœ… Lists for mutable collections
cart_items = ["apple", "banana"]
cart_items.append("orange")  # Can modify

# βœ… Tuples as dict keys (lists cannot be dict keys)
location_data = {(40.7128, -74.0060): "New York"}