Skip to content
PythonWorking with Collectionsbeginner18 min read

Tuples and Immutability

Master tuple creation, indexing, unpacking, immutability, and common errors with step-by-step Python examples.

In this lesson, you will learn

  • ✓Create tuples using parentheses and understand why a single-element tuple needs a trailing comma.
  • ✓Access tuple elements using positive and negative indexes.
  • ✓Unpack tuple elements into variables and understand the requirement for matching numbers of values.
  • ✓Explain tuple immutability and distinguish it from the mutability of objects stored inside a tuple.
  • ✓Trace tuple operations, predict exact outputs, and identify common tuple-related errors.

1. Creating tuples

A tuple is an ordered collection of elements. Its order is preserved, and its elements can be accessed by index. A tuple can contain values of different data types, including integers, strings, and other collections.

Parentheses are commonly used to write tuples, as in point = (3, 5). Python also recognizes a tuple through the comma-separated expression itself, so parentheses are not always required.

An empty tuple can be created with empty parentheses: empty = (). A tuple containing one element needs a trailing comma. For example, single = (7,) creates a one-element tuple, while single = (7) simply evaluates to the integer 7.

Tuples are useful for representing related values that belong together, such as coordinates, RGB color components, or a fixed collection of returned values.

Creating a tuple with multiple elements

Creating a tuple with multiple elements
python
point = (3, 5)
print(point)
print(type(point))
Output
(3, 5) <class 'tuple'>

The expression (3, 5) creates a tuple containing two integers. print(point) displays both elements in their original order. type(point) returns the type object tuple, which print() displays as <class 'tuple'>.

Note

The comma is what makes a comma-separated expression a tuple. Parentheses help make tuple expressions clear, but a single-element tuple must contain a trailing comma.

2. Accessing tuple elements

Tuples support indexing in the same way as lists. Indexing starts at 0, so the first element is at index 0, the second is at index 1, and so on.

Negative indexes count from the end. Index -1 refers to the last element, -2 refers to the second-to-last element, and so on.

You can also use slicing to obtain a portion of a tuple. The slice tuple[start:stop] includes the element at start but excludes the element at stop. Slicing creates a new tuple and does not modify the original tuple.

Accessing an index that is outside the tuple's valid range raises IndexError. An empty tuple has no valid element indexes, although slicing an empty tuple is valid.

Using positive indexes

Using positive indexes
python
colors = ('red', 'green', 'blue')
print(colors[0])
print(colors[1])
print(colors[2])
Output
red green blue

Index 0 accesses 'red', the first element. Index 1 accesses 'green', the second element. Index 2 accesses 'blue', the third element.

Caution

A tuple cannot be indexed outside its valid range. For example, (10, 20)[2] raises IndexError because the valid indexes are 0, 1, -1, and -2.

3. Tuple unpacking

Tuple unpacking assigns the elements of an iterable to multiple variables in a single assignment. For example, x, y = (3, 5) assigns 3 to x and 5 to y.

The variables receive the values in order. The first value goes to the first target, the second value goes to the second target, and so on.

For ordinary unpacking, the number of values on the right must match the number of assignment targets on the left. If the counts differ, Python raises ValueError.

Unpacking is not limited to tuples. It also works with other iterables, including lists. In this lesson, tuples provide a clear example of the technique.

Unpacking two values

Unpacking two values
python
point = (3, 5)
x, y = point
print(x)
print(y)
Output
3 5

point contains two elements: 3 and 5. The assignment x, y = point unpacks the two values in order. The variable x receives 3, and y receives 5. The two print() statements display the values on separate lines.

Note

Unpacking is useful when a function returns multiple values or when a tuple represents a record, such as a point with x and y coordinates.

4. Immutability: what can and cannot change?

A tuple is immutable. Once it has been created, you cannot replace, add, or remove its element slots. For example, assigning point[0] = 10 raises TypeError.

Immutability does not mean that every object contained in a tuple must itself be immutable. A tuple can hold a reference to a mutable object, such as a list. That list can still be modified, even though the tuple's element reference cannot be reassigned.

This distinction is important: a tuple containing a list is not deeply immutable. The tuple still refers to the same list object, but the contents of that list can change.

If you need to change the collection's membership or replace its elements, a list may be a better choice. A tuple is suitable when the grouping and ordering of its element references should remain fixed.

A tuple element cannot be reassigned

A tuple element cannot be reassigned
python
point = (3, 5)
point[0] = 10
Output
TypeError: 'tuple' object does not support item assignment

The tuple initially contains 3 and 5. The assignment attempts to replace the element at index 0. Tuples do not support item assignment, so Python raises TypeError. The example intentionally demonstrates an error and therefore does not produce a normal printed result.

Caution

Do not conclude that a tuple is deeply immutable simply because the tuple itself cannot be reassigned. If it contains a list or another mutable object, that object's contents may still change.

5. Common operations and edge cases

Tuples support several useful operations. len(tuple_value) returns the number of elements, the in operator checks whether a value is present, and the count() and index() methods provide information about matching elements.

count(value) returns the number of elements equal to value. index(value) returns the index of the first matching element and raises ValueError if no match exists.

The plus operator can concatenate tuples, and the multiplication operator can repeat their elements. Both operations create a new tuple rather than modifying an existing tuple.

Because tuples are immutable, they do not have list methods such as append(), extend(), or remove(). Calling such a method on a tuple raises AttributeError.

Using len(), count(), and index()

Using len(), count(), and index()
python
numbers = (10, 20, 10, 30)
print(len(numbers))
print(numbers.count(10))
print(numbers.index(20))
Output
4 2 1

len(numbers) returns 4 because the tuple contains four elements. count(10) returns 2 because 10 appears twice. index(20) returns 1 because 20 is at index 1.

Note

Tuple operations that produce a new tuple do not modify the original tuple. Keep this separate from mutating a list stored inside a tuple, which changes that nested list object.

6. Step-by-step dry run

A dry run tracks the value of each variable after every statement. This is especially useful for unpacking because it makes the relationship between tuple positions and variable names explicit.

Follow the example below and note that unpacking assigns values; it does not remove elements from the tuple.

Trace tuple creation and unpacking

Trace tuple creation and unpacking
python
point = (3, 5)
x, y = point
total = x + y
print(x)
print(y)
print(total)
Output
3 5 8

First, point refers to the tuple (3, 5). Next, unpacking assigns 3 to x and 5 to y. The expression x + y evaluates to 8, which is assigned to total. The print() statements display 3, 5, and 8 on separate lines. The tuple remains unchanged throughout the example.

Caution

When tracing unpacking, do not swap values accidentally. In x, y = (3, 5), x receives 3 and y receives 5 because Python assigns values from left to right.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Writing (7) when a one-element tuple is required.

Why it happens: Parentheses alone do not create a tuple; the comma is what distinguishes a one-element tuple from a parenthesized value.

Incorrect Approach
script.py
python
Writing (7) when a one-element tuple is required.
Correct Solution
script.py
python
Use (7,). The comma creates the tuple; parentheses alone do not.

Key takeaway: Use (7,). The comma creates the tuple; parentheses alone do not.

#2 Trying to assign a new value to a tuple element.

Why it happens: Tuples are immutable, so an existing element cannot be reassigned; create a new tuple if the sequence itself must change.

Incorrect Approach
script.py
python
Trying to assign a new value to a tuple element.
Correct Solution
script.py
python
Tuples are immutable. Create a new tuple if you need different element values, or use a list if the collection must support item assignment.

Key takeaway: Tuples are immutable. Create a new tuple if you need different element values, or use a list if the collection must support item assignment.

#3 Assuming that a tuple cannot contain mutable objects.

Why it happens: Tuple immutability applies to the tuple's element references, not to mutable objects stored inside it; a contained list can still be changed.

Incorrect Approach
script.py
python
Assuming that a tuple cannot contain mutable objects.
Correct Solution
script.py
python
A tuple can contain a list or another mutable object. The tuple's element reference cannot be reassigned, but the referenced object's contents may change.

Key takeaway: A tuple can contain a list or another mutable object. The tuple's element reference cannot be reassigned, but the referenced object's contents may change.

#4 Unpacking a different number of values than there are assignment targets.

Why it happens: Tuple unpacking matches iterable values to target names, so a mismatch raises ValueError unless starred unpacking handles the extra values.

Incorrect Approach
script.py
python
Unpacking a different number of values than there are assignment targets.
Correct Solution
script.py
python
For ordinary unpacking, make the number of targets match the number of supplied values, or deliberately use starred unpacking when appropriate.

Key takeaway: For ordinary unpacking, make the number of targets match the number of supplied values, or deliberately use starred unpacking when appropriate.

#5 Assuming tuple indexes start at 1.

Why it happens: Like other Python sequences, tuples use zero-based indexing, so their first element is at index 0.

Incorrect Approach
script.py
python
Assuming tuple indexes start at 1.
Correct Solution
script.py
python
Positive indexing starts at 0. Use index 0 for the first element and index -1 for the last.

Key takeaway: Positive indexing starts at 0. Use index 0 for the first element and index -1 for the last.

#6 Calling a list method such as append() on a tuple.

Why it happens: Tuples do not support in-place list mutation methods such as append(); concatenate tuples or build a new sequence instead.

Incorrect Approach
script.py
python
Calling a list method such as append() on a tuple.
Correct Solution
script.py
python
Tuples do not provide list mutation methods. Use a list when you need to add or remove elements in place.

Key takeaway: Tuples do not provide list mutation methods. Use a list when you need to add or remove elements in place.

#7 Assuming index() returns every matching position.

Why it happens: tuple.index(value) returns the first matching position only; use a comprehension or enumerate() to find all matching positions.

Incorrect Approach
script.py
python
Assuming index() returns every matching position.
Correct Solution
script.py
python
index(value) returns the first matching index. Use an appropriate loop or another approach if all matching positions are needed.

Key takeaway: index(value) returns the first matching index. Use an appropriate loop or another approach if all matching positions are needed.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is a tuple in Python?
Answer:
A tuple is an ordered collection of elements. It supports indexing, slicing, iteration, and unpacking. Unlike a list, a tuple does not support reassignment of its element slots after creation.
Q2:What is the difference between a tuple and a list?
Answer:
Both are ordered collections and support indexing. Lists are mutable and support operations such as append(), insert(), and remove(). Tuples are immutable with respect to their element slots and do not provide these list mutation methods.
Q3:Why does (7,) create a tuple while (7) does not?
Answer:
The comma identifies the tuple expression. Parentheses alone group the integer expression, so (7) evaluates to 7, whereas (7,) creates a tuple containing one integer.
Q4:What is tuple unpacking?
Answer:
Tuple unpacking assigns elements from a tuple to multiple variables in order. For example, x, y = (3, 5) assigns 3 to x and 5 to y. In ordinary unpacking, the number of values must match the number of targets.
Q5:Can a tuple contain a mutable object?
Answer:
Yes. A tuple can contain a list or another mutable object. You cannot reassign the tuple's element to a different object, but you can mutate the contents of a mutable object referenced by that element.
Q6:How do count() and index() differ?
Answer:
count(value) returns the number of elements equal to value. index(value) returns the index of the first matching element and raises ValueError if no match is found.

Key takeaways

  • Tuples are ordered collections that support indexing, slicing, iteration, and unpacking.
  • Use a trailing comma to create a one-element tuple, as in (7,).
  • Positive indexes start at 0, while negative indexes count backward from the end.
  • Unpacking assigns values in order; ordinary unpacking requires the number of values to match the number of targets.
  • Tuples do not support reassignment of their element slots, but mutable objects stored inside them can still change.
  • count() counts matching values, and index() returns the first matching index.
  • Tuple operations such as concatenation create new tuples rather than modifying the original tuple.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: