On this page

Tuples

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

What a Tuple Is​

A tuple is an ordered, immutable sequence of values. Like a list, it can store multiple items, but unlike a list, its contents cannot be changed after creation. This immutability makes tuples ideal for fixed collections of data, function returns, and situations where data integrity matters.

Tuples use parentheses:


point = (10, 20)

colors = ("red", "green", "blue")

mixed = (1, "two", False)

Tuples preserve order, allow duplicates, and can contain any Python object.

Creating Tuples​

You can create tuples in several ways:


empty = ()

single = (42,)          # note the comma

values = (1, 2, 3)

converted = tuple("abc")   # ('a', 'b', 'c')

A single‑element tuple must include a trailing comma; otherwise, Python treats it as a normal value.

Accessing Tuple Elements (Indexing)​

Tuples support the same indexing rules as lists.


items = ("a", "b", "c")



print(items[0])   # 'a'

print(items[-1])  # 'c'

Indexing is essential for retrieving specific elements.

Slicing Tuples​

Tuples support slicing just like lists.


numbers = (10, 20, 30, 40, 50)



print(numbers[1:4])   # (20, 30, 40)

print(numbers[:3])    # (10, 20, 30)

print(numbers[3:])    # (40, 50)

Slicing returns a new tuple, preserving immutability.

Tuple Immutability​

Tuples are immutable, meaning their contents cannot be changed.

Invalid operations:


values = (1, 2, 3)

# values[1] = 10     # TypeError

# values.append(4)   # AttributeError

Immutability provides safety: once created, the data cannot be altered accidentally.

Tuple Packing and Unpacking​

Python supports packing and unpacking, a powerful feature for assigning multiple values at once.

Packing​


coords = 10, 20, 30

Unpacking​


x, y, z = coords

Unpacking is widely used in loops, function returns, and structured data handling.

Returning Multiple Values from Functions​

Functions often return tuples to provide multiple results.


def stats(a, b):

    return a + b, a * b



total, product = stats(3, 4)

This pattern is common in real‑world Python code.

Looping Through Tuples​

Tuples are iterable, so you can use a for loop to process each element.


for item in ("x", "y", "z"):

    print(item)

Iteration works exactly like it does with lists.

When to Use Tuples Instead of Lists​

Use a tuple when:

Tuples communicate intent: “this collection is fixed.”

Why Tuples Matter​

Tuples provide a simple, efficient, and safe way to store ordered data that must remain unchanged. They support indexing, slicing, iteration, and packing/unpacking, making them essential for clean, predictable program design. Understanding tuples prepares you for more advanced structures such as dictionaries, sets, and custom data models.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Lists

Next

Dictionaries