10.8. Lists are MutableΒΆ

Unlike strings, lists are mutable. This means we can change an item in a list by accessing it directly as part of the assignment statement. Using the indexing operator (square brackets) on the left side of an assignment, we can update one of the list items.

An assignment to an element of a list is called item assignment. Item assignment does not work for strings. Recall that strings are immutable.

Here is the same example in codelens so that you can step through the statements and see the changes to the list elements.

Activity: CodeLens 10.8.2 (item_assign)

By combining assignment with the slice operator we can update several elements at once.

We can also remove elements from a list by assigning the empty list to them.

Before you keep reading...

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

We can even insert elements into a list by squeezing them into an empty slice at the desired location.

Check your understanding

You have attempted 1 of 7 activities on this page