We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Immutability

In FP, we love to make data immutable. Immutable values can't be changed after they're created so they're easier to think about.

Say you're trying to fix a bug where a user doesn't have as much money in their account as they should. If twenty different functions all modify that same variable, it's going to be a nightmare to figure out which one is the culprit!

Tuples vs. Lists

Tuples and lists are both ordered collections, but lists are mutable:

ages: list[int] = [16, 21, 30]
ages.append(80)
# [16, 21, 30, 80]

while tuples are immutable:

ages: tuple[int, ...] = (16, 21, 30)
# (16, 21, 30)
more_ages: tuple[int, ...] = (80,)
# (80,)
all_ages: tuple[int, ...] = ages + more_ages
# (16, 21, 30, 80)

Here, all_ages is a new tuple that has the values from ages and more_ages, but the original tuples are unchanged.

Assignment

There's a bug in the add_prefix function! It's supposed to add a prefix to a document, then return a new tuple containing the provided documents and the updated document as the last element.

Fix the bug by adding a comma like this: (new_doc,) so that Python recognizes it as a single-element tuple.