Python online course

Python Tuples: Immutable Ordered Collections

Learn how Python tuples work, including creation, indexing, slicing, immutability, unpacking, dictionary iteration, and tuple versus list choices.

A tuple is an ordered Python collection that stores multiple values under one variable name. Each value has a position, called an index, and the values remain in their insertion order.

Tuples are immutable: after a tuple is created, its item references cannot be replaced, inserted, or removed in place. This makes tuples useful for fixed or read-only collections, while lists are usually better when the collection must change.

What Is a Tuple?

A tuple groups related values into one object. For example, an RGB color can be represented by three fixed numeric values:

color = (255, 128, 0)
print(color)

This tuple contains three items. The first item is at index 0, the second is at index 1, and the third is at index 2.

Because tuples are ordered, Python preserves the sequence in which their items were stored. Because they are immutable, the tuple itself cannot be changed after creation.

Creating Tuples

Tuple literals normally use comma-separated values enclosed in parentheses. The parentheses improve readability, but the commas are what define the tuple.

numbers = (2, 4, 2, 5)
colors = ("red", "green", "blue")
mixed = (42, "Python", 3.14, True)

Tuples can contain numbers, strings, Boolean values, and other Python objects. An empty tuple has no items:

empty = ()

One-item tuples

A one-item tuple requires a trailing comma. Parentheses without a comma simply group an expression:

single_value = (42,)
not_a_tuple = (42)

print(type(single_value))  # tuple
print(type(not_a_tuple))   # int

The comma is essential. You can also create a tuple without parentheses by separating values with commas, although parentheses are normally clearer:

point = 10, 20
print(point)  # (10, 20)

Accessing Tuple Items

Tuple indexing is zero-based, meaning the first item has index 0. This is the same indexing convention used by other Python sequences.

my_numbers = (2, 4, 2, 5)

print(my_numbers[0])  # 2
print(my_numbers[1])  # 4
print(my_numbers[3])  # 5

Negative indexes count from the end. Index -1 refers to the last item, -2 refers to the item before it, and so on.

print(my_numbers[-1])  # 5
print(my_numbers[-2])  # 2

Slicing a tuple

Slicing selects a range of sequence items using a start index, a stop index, and an optional step. The stop index is not included in the result.

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

print(values[1:4])  # (20, 30, 40)
print(values[:3])   # (10, 20, 30)
print(values[2:])   # (30, 40, 50)
print(values[::2])  # (10, 30, 50)

A slice produces a new tuple. It does not modify the original tuple.

Invalid indexes

An index must identify an existing position. Trying to access a position outside the valid range raises IndexError:

values = (10, 20, 30)
print(values[3])
# IndexError: tuple index out of range

For a tuple with three items, the valid positive indexes are 0, 1, and 2. Check len(values) and remember that indexing starts at zero.

Tuple Immutability

Immutable means that a tuple's item references cannot be replaced, added, or removed after creation. Assigning a new value to a tuple index is not allowed:

coordinates = (10, 20)
coordinates[0] = 99
# TypeError: 'tuple' object does not support item assignment

The error is a TypeError, which indicates that the attempted operation is not supported for that object. To represent changed values, create a new tuple:

coordinates = (10, 20)
coordinates = (99, coordinates[1])
print(coordinates)  # (99, 20)

Alternatively, use a list when replacing, adding, or removing items is part of the task.

A mutable object inside a tuple

Immutability applies to the tuple's item references. An item can refer to a mutable object, such as a list. The tuple cannot replace the list reference, but the list's contents can still change:

data = ("settings", [1, 2])
data[1].append(3)

print(data)  # ('settings', [1, 2, 3])

The tuple still contains the same list object at index 1; the list itself changed. This is why “immutable tuple” does not mean that every nested object is automatically immutable.

Tuple and List Comparison

FeatureTupleList
Literal syntax(1, 2, 3)[1, 2, 3]
Whether items can be changedNo; the tuple is immutableYes; list items can be replaced, inserted, or removed
Common use casesFixed coordinates, constants, and read-only recordsCollections that grow, shrink, or change
Available mutating operationsNone for the tuple itselfMethods such as append(), remove(), and sort()
Suitability as a dictionary key when contents are hashableYes, if every contained value is hashableNo; lists are not hashable

For a more detailed comparison with mutable collections, see what Python lists are and how to modify lists.

Working with Tuples

Length and membership

Use len() to count tuple items. Use in to test whether a value exists and not in to test whether it does not exist.

days = ("Monday", "Tuesday", "Wednesday")

print(len(days))             # 3
print("Tuesday" in days)     # True
print("Sunday" not in days)  # True

Looping over tuple values

A for loop visits each tuple item in order:

my_numbers = (2, 4, 2, 5)

for number in my_numbers:
    print(number)

Use enumerate() when both the index and the item are needed:

names = ("Ada", "Lin", "Sam")

for index, name in enumerate(names):
    print(index, name)

Tuple methods

Tuples have two commonly used methods. count() returns how many times a value occurs. index() returns the index of the first matching value.

values = (2, 4, 2, 5, 2)

print(values.count(2))  # 3
print(values.index(5))  # 3

If index() cannot find the requested value, it raises ValueError.

Concatenation and repetition

The + operator concatenates tuples, and the * operator repeats them. Both operations create a new tuple; they do not alter either original tuple.

first = (1, 2)
second = (3, 4)

combined = first + second
repeated = first * 3

print(combined)  # (1, 2, 3, 4)
print(repeated)  # (1, 2, 1, 2, 1, 2)
print(first)     # (1, 2)

Tuple Packing and Unpacking

Tuple packing

Tuple packing combines multiple values into one tuple. The assignment below packs three values into person:

person = "Ada", 36, "programmer"
print(person)  # ('Ada', 36, 'programmer')

Parentheses can make the operation easier to read:

person = ("Ada", 36, "programmer")

Tuple unpacking

Tuple unpacking assigns the items in a tuple to separate variables:

x, y = (10, 20)
print(x)  # 10
print(y)  # 20

Normally, the number of target variables must match the number of tuple items:

values = (10, 20, 30)
a, b, c = values

If the counts differ, Python raises a ValueError indicating that there were too many or too few values to unpack.

Starred unpacking

Place an asterisk before one target to collect the remaining values into a list:

numbers = (1, 2, 3, 4, 5)
first, *middle, last = numbers

print(first)   # 1
print(middle)  # [2, 3, 4]
print(last)    # 5

The starred target can collect zero or more remaining values, but only one starred target is allowed in an unpacking assignment.

An underscore is a conventional throwaway target when a value is not needed:

name, _, role = ("Ada", 36, "programmer")
print(name, role)

Tuples in Dictionary Iteration

A dictionary stores key-value pairs. Its items() method produces pairs that can be handled as two-value tuples during iteration.

scores = {"Ada": 95, "Lin": 88}

for name, score in scores.items():
    print(name, score)

Here, each iteration provides one key-value pair, and tuple unpacking assigns the key to name and the value to score.

These dictionary loops have different purposes:

  • for key in scores: iterates over dictionary keys, which is also the default dictionary iteration.
  • for value in scores.values(): iterates over values.
  • for key, value in scores.items(): iterates over key-value pairs and unpacks each pair into two variables.
  • for item in some_tuple: iterates directly over the values in a tuple.

For more dictionary practice, see what Python dictionaries are and how to loop through a dictionary.

When to Choose a Tuple Instead of a List

Choose a tuple when the collection represents values that should remain fixed. Examples include:

  • A coordinate such as (10, 20).
  • An RGB color such as (255, 128, 0).
  • Configuration-like constants.
  • A fixed set of days or months.
  • A record whose number and order of fields should not change.

Choose a list when your program must add, remove, sort, or replace items. For example, a shopping cart usually needs a list because its contents change.

Tuples as dictionary keys and set members

A value is hashable when it can be used as a dictionary key or set element because its hash value remains stable. A tuple can be a dictionary key or set member only when all of its contained values are hashable.

locations = {
    (40.7, -74.0): "New York",
    (51.5, -0.1): "London"
}

print(locations[(40.7, -74.0)])

A tuple containing a list is not hashable:

key = ("tags", ["python", "beginner"])
lookup = {key: "example"}
# TypeError: unhashable type: 'list'

Use only immutable, hashable contents, such as strings, numbers, or nested tuples whose contents are also hashable.

Common Tuple Operations

OperationExample patternResult or purpose
Indexingitems[1]Gets the item at index 1
Negative indexingitems[-1]Gets the last item
Slicingitems[1:4]Returns a selected range as a new tuple
Lengthlen(items)Counts the items
Membership testvalue in itemsReturns True if the value occurs
count()items.count(value)Counts matching values
index()items.index(value)Finds the first matching index
Concatenationfirst + secondCreates a tuple containing both sequences
Repetitionitems * 2Creates a tuple with repeated items

Troubleshooting Tuple Problems

Trying to replace an item

Symptom: Python raises TypeError saying that a tuple does not support item assignment.

Cause: Tuples are immutable.

Resolution: Create a new tuple with the desired values, or use a list if the values must change.

Forgetting the comma in a one-item tuple

Symptom: The variable contains the single value rather than a tuple.

Cause: Parentheses alone group an expression; they do not create a tuple.

Resolution: Add a trailing comma, such as (value,).

Accessing beyond the end

Symptom: Python raises IndexError: tuple index out of range.

Cause: The requested index does not exist.

Resolution: Check len(), remember zero-based indexing, and use a valid positive or negative index.

Unpacking the wrong number of values

Symptom: Python raises ValueError because there are too many or too few values to unpack.

Cause: The target variables do not match the tuple's item count.

Resolution: Match the number of variables or use starred unpacking to collect remaining values.

Using a tuple containing a list as a dictionary key

Symptom: Python raises TypeError stating that a list is unhashable.

Cause: The list inside the tuple is mutable, so the complete tuple cannot be hashed.

Resolution: Replace the list with a hashable value, such as a tuple containing only hashable items.

Key Points

  • A tuple stores multiple values under one variable name.
  • Tuples are ordered and use zero-based indexing.
  • Commas define tuples; a one-item tuple needs a trailing comma.
  • Tuples are immutable, so their item references cannot be changed in place.
  • Use indexing, negative indexing, slicing, membership tests, loops, count(), and index() to work with tuple data.
  • Concatenation and repetition create new tuples.
  • Tuple packing combines values, while unpacking assigns values to separate variables.
  • Use tuples for fixed collections and lists for collections that must change.
  • A tuple is suitable as a dictionary key or set member only when all contained values are hashable.