Advertisement
❮ Previous: Python Lists & List Comprehensions Next: Python Sets & Set Operations ❯

Python Tuples & Unpacking

What is a Python Tuple?

A tuple is a built-in data structure used to store an ordered collection of items. Unlike lists, tuples are immutable—meaning once a tuple is created, its elements cannot be modified, added, or removed.

Tuples are defined by enclosing items in parentheses (), separated by commas.

# Creating tuples
my_tuple = ("apple", "banana", "cherry")
numbers = (1, 2, 3, 4, 5)
mixed_tuple = (1, "hello", 3.14, True)

Try this code ❯


Key Characteristics of Tuples

The Single-Element Tuple Quirk: To create a tuple with only one item, you must include a trailing comma. Otherwise, Python treats the parentheses as standard mathematical grouping:

not_a_tuple = ("hello")      # Type: str
actual_tuple = ("hello",)    # Type: tuple


Advertisement

Tuple Unpacking

Unpacking allows you to assign the elements of a tuple directly to multiple variables in a single clean statement.

# Basic unpacking
coordinate = (10, 20, 30)
x, y, z = coordinate

print(x)  # Output: 10
print(y)  # Output: 20
print(z)  # Output: 30

Try this code ❯

Extended Unpacking with the Star (*) Operator

If you want to capture remaining elements or handle a variable number of items, you can use the * operator during unpacking:

scores = (95, 88, 76, 92, 85)

first, *middle, last = scores

print(first)   # Output: 95 (first item)
print(last)    # Output: 85 (last item)
print(middle)  # Output: [88, 76, 92] (collected into a list)

Try this code ❯

Swapping Variables

Tuples make swapping variable values elegant without needing a temporary variable:

a = 5
b = 10

a, b = b, a  # Packed and unpacked implicitly
print(a, b)  # Output: 10 5

Try this code ❯


Advertisement

Built-in Tuple Methods

Because tuples are immutable, they only have two built-in methods:

Method Description Example
count() Returns the number of times a specified value occurs my_tuple.count(3)
index() Searches the tuple for a specified value and returns its position my_tuple.index("banana")

Advertisement

Lists vs. Tuples: When to Use Which?

Feature Lists ([]) Tuples (())
Mutability Mutable (can change) Immutable (read-only)
Performance Slightly slower to create/iterate Faster and more memory-efficient
Safety Prone to accidental mutation Safe from unintended side effects
Use Case Collections of items that change Fixed records, coordinates, dictionary keys
❮ Previous: Python Lists & List Comprehensions Next: Python Sets & Set Operations ❯
Advertisement