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 strive to make data immutable. Once a value is created, it cannot be changed. Mutable data, on the other hand, can be changed after it's created.

Who Cares?

Immutable data is easier to think about and work with. When 10 different functions have access to the same variable, and you're debugging a problem with that variable, you have to consider the possibility that any of those functions could have changed the value.

When a variable is immutable, you can be sure that it hasn't changed since it was created. It's a helluva lot easier to work with.

Generally speaking, immutability means fewer bugs and more maintainable code.

Tuples vs. Lists

Tuples and lists are both ordered collections of values, but tuples are immutable and lists are mutable.

You can append to a list, but you can not append to a tuple. You can create a new copy of a tuple using values from an existing tuple, but you can't change the existing tuple.

Lists Are Mutable

ages: list[int] = [16, 21, 30]
# 'ages' is being changed in place
ages.append(80)
# [16, 21, 30, 80]

Tuples Are Immutable

ages: tuple[int, ...] = (16, 21, 30)
# note the comma after 80! It's required for a single-element tuple
more_ages: tuple[int, ...] = (80,)
# 'all_ages' is a brand new tuple
all_ages: tuple[int, ...] = ages + more_ages
# (16, 21, 30, 80)

# or we can even reassign the same variable to point to a new tuple:
ages = ages + more_ages
# (16, 21, 30, 80)

The ... in tuple[int, ...] means the tuple can contain any number of int values.

Assignment

Complete the add_prefix function. Return a new tuple with document appended as X. document, where X is its index in the tuple.

The tests begin with an empty documents tuple and repeatedly pass each returned tuple back into add_prefix() as the next call's second argument. You don't need to write a loop.