Learn Without Walls
← Previous Lesson Lesson 3 of 4 Next Lesson →

Lesson 8.3: Tuples and Immutability

What You'll Learn

1. What is a Tuple?

A tuple is an ordered, immutable sequence of values. It works just like a list, except you cannot change it after it is created — no adding, removing, or modifying elements.

Tuple: An ordered, immutable sequence created with parentheses () or just commas. Once created, its contents cannot be changed.
# Creating a tuple with parentheses
colors = ("red", "green", "blue")
print(colors)
print(type(colors))

# Tuples can hold mixed types
record = ("Alice", 25, 3.8, True)
print(record)
('red', 'green', 'blue') <class 'tuple'> ('Alice', 25, 3.8, True)

2. Creating Tuples

With Parentheses

point = (3, 7)
weekdays = ("Mon", "Tue", "Wed", "Thu", "Fri")

Without Parentheses (Tuple Packing)

# The comma is what makes it a tuple, not the parentheses
coordinates = 4, 5
print(type(coordinates))
<class 'tuple'>

Single-Element Tuple (The Trailing Comma)

Common Mistake: A single value in parentheses is not a tuple — you need a trailing comma!
# This is NOT a tuple - just a string in parentheses
not_a_tuple = ("hello")
print(type(not_a_tuple))

# This IS a tuple - note the trailing comma
is_a_tuple = ("hello",)
print(type(is_a_tuple))
<class 'str'> <class 'tuple'>

Empty Tuple

empty = ()
also_empty = tuple()
print(len(empty))
0

Converting Other Sequences to Tuples

my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple)

my_string = "abc"
char_tuple = tuple(my_string)
print(char_tuple)
(1, 2, 3) ('a', 'b', 'c')

3. Accessing Tuple Elements

Tuples support the same indexing and slicing as lists:

fruits = ("apple", "banana", "cherry", "date")

# Indexing
print(fruits[0])
print(fruits[-1])

# Slicing
print(fruits[1:3])

# Length
print(len(fruits))

# Membership test
print("banana" in fruits)
apple date ('banana', 'cherry') 4 True

What You Cannot Do

fruits = ("apple", "banana", "cherry")

# These will all raise TypeError:
# fruits[0] = "avocado"    # Can't change elements
# fruits.append("date")    # No append method
# del fruits[1]            # Can't delete elements
Immutable: Once a tuple is created, you cannot add, remove, or change its elements. This is the key difference between tuples and lists.

4. Tuple Unpacking

One of the most powerful tuple features is unpacking — assigning each element to a separate variable in one line:

# Basic unpacking
point = (3, 7)
x, y = point
print(f"x = {x}, y = {y}")

# Unpacking with more values
name, age, major = ("Alice", 20, "CS")
print(f"{name} is {age}, studying {major}")
x = 3, y = 7 Alice is 20, studying CS

Swapping Variables

Tuple unpacking makes swapping values elegant:

a = 10
b = 20

# Swap without a temporary variable!
a, b = b, a
print(f"a = {a}, b = {b}")
a = 20, b = 10

Unpacking in Loops

students = [
    ("Alice", 95),
    ("Bob", 87),
    ("Carol", 92)
]

for name, score in students:
    print(f"{name}: {score}")
Alice: 95 Bob: 87 Carol: 92
Rule: The number of variables on the left must match the number of elements in the tuple, or Python will raise a ValueError.

5. Tuple Methods

Because tuples are immutable, they have only two methods:

numbers = (1, 3, 5, 3, 7, 3)

# count() - how many times a value appears
print(numbers.count(3))

# index() - position of first occurrence
print(numbers.index(5))
print(numbers.index(3))  # first occurrence of 3
3 2 1

You can also use built-in functions on tuples:

nums = (10, 20, 5, 30, 15)

print(min(nums))
print(max(nums))
print(sum(nums))
print(sorted(nums))  # returns a LIST, not a tuple
5 30 80 [5, 10, 15, 20, 30]

6. Why Immutability Matters

At first, it may seem like tuples are just limited lists. But immutability provides real benefits:

Benefits of Tuples

  • Safety: Data that should not change (coordinates, RGB colors, database records) stays protected
  • Dictionary Keys: Tuples can be used as dictionary keys because they are immutable; lists cannot
  • Performance: Tuples are slightly faster than lists and use less memory
  • Signal Intent: Using a tuple tells other programmers "this data should not be modified"
# Tuples can be dictionary keys (lists cannot!)
locations = {
    (40.7, -74.0): "New York",
    (34.0, -118.2): "Los Angeles",
    (41.9, -87.6): "Chicago"
}

print(locations[(34.0, -118.2)])
Los Angeles

Check Your Understanding

Question: Which of these creates a single-element tuple?

  1. t = (42)
  2. t = (42,)
  3. t = [42]
  4. t = tuple(42)

Answer: b) t = (42,)

Option (a) is just the integer 42 in parentheses. Option (c) creates a list. Option (d) would raise a TypeError because tuple() expects an iterable, not a single integer.

Try It Yourself

  1. Create a tuple of your three favorite foods
  2. Use indexing to print the second food
  3. Try to change the first element — observe the error
  4. Unpack the tuple into three separate variables and print each one
  5. Use the tuple as a dictionary key mapped to a rating

Key Takeaways

← Previous: Dictionary Methods Next: Choosing Data Structures →