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
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
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
Index 0 accesses 'red', the first element. Index 1 accesses 'green', the second element. Index 2 accesses 'blue', the third element.
Caution
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
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
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
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
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()
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
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
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
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.
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.
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.
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.
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.
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.
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.
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.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is a tuple in Python?
Q2:What is the difference between a tuple and a list?
Q3:Why does (7,) create a tuple while (7) does not?
Q4:What is tuple unpacking?
Q5:Can a tuple contain a mutable object?
Q6:How do count() and index() differ?
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.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: