...

/

Changing Immutable Objects

Changing Immutable Objects

Learn about ways to process immutable data.

Changing immutable objects

We do sometimes need to “change” immutable objects. Of course, you can’t actually do that, but what you can do is create a copy of the original object, modified in some way. There are various ways of doing this, which we will explore here.

Let’s start with a simple example. The tail function takes a list and returns a list that is identical except that the first term is removed. So, [1, 2, 3] becomes [2, 3]. Here is how we might do this:

Press + to interact
def tail(x):
if x: # If x is already empty do nothing
del x[0]
k = [1, 2, 3]
tail(k)
print(k) # [2, 3]

This only works for lists. The list is passed into the function and modified in place. But, for reasons we discussed previously, this will fail if we pass a tuple as the parameter. ...

Access this course and 1400+ top-rated courses and projects.