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.

 
1
fruit = ["banana", "apple", "cherry"]
2
print(fruit)
3
4
fruit[0] = "pear"
5
fruit[-1] = "orange"
6
print(fruit)
7

(ch09_7)

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 thru the statements and see the changes to the list elements.

Python 3.3
1fruit = ["banana", "apple", "cherry"]
2
3fruit[0] = "pear"
4fruit[-1] = "orange"
Step 1 of 3
line that has just executed

next line to execute

Visualized using Online Python Tutor by Philip Guo
Frames
Objects

(item_assign)

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

4
 
1
alist = ['a', 'b', 'c', 'd', 'e', 'f']
2
alist[1:3] = ['x', 'y']
3
print(alist)
4

(ch09_8)

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

4
 
1
alist = ['a', 'b', 'c', 'd', 'e', 'f']
2
alist[1:3] = []
3
print(alist)
4

(ch09_9)

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

6
 
1
alist = ['a', 'd', 'f']
2
alist[1:1] = ['b', 'c']
3
print(alist)
4
alist[4:4] = ['e']
5
print(alist)
6

(ch09_10)

Check your understanding

rec-5-1: What is printed by the following statements?

alist = [4,2,8,6,5]
alist[2] = True
print(alist)




Next Section - List Deletion