This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 3: More on lists

Adding to and deleting from list

face Josiah Wang

You may have noticed from the previous page that you can modify the values of a list.

list is a mutable object. “Mutable” comes from the word mutate. Think mutants.

Teenage Mutant Ninja Turtles

Image credits

Note that this is different from reassigning variables to another object (where you point to a new object). You can modify parts of the list directly.

For example, you can add new items to the end of the list by using append(). Note that append() modifies numbers directly in the example below. We are not returning a new object by calling append() like what we would usually do with functions. We will discuss this weird numbers.append() notation in the next lesson, for now you just need to know that this is how you append new items to your list!

>>> numbers = []          # this creates a new empty list
>>> numbers.append(6)
>>> print(numbers)
[6]
>>> numbers.append(2)
>>> print(numbers)
[6, 2]

You can also delete items from a list with the del operator.

>>> numbers = [1, 2, 3]
>>> print(numbers)
[1, 2, 3]
>>> del numbers[1]
>>> print(numbers)
[1, 3]

Hopefully you are not tired of quizzes yet! This is a short one!

1 2 3

Question 1

What is the output of the following code snippet? Type Error if it results in an error.

1
2
3
4
numbers = [5, 7]
numbers.append(2)
numbers.append(1)
print(numbers)

[5, 7, 2, 1]
Explanation:

Quite straightforward. 2 and 1 are appended to the end of numbers.

Question 2

What is the output of the following code snippet? Type Error if it results in an error.

1
2
3
4
5
6
numbers = [5, 7]
numbers.append(2)
del numbers[1]
numbers.append(1)
del numbers[1]
print(numbers)

[5, 1]
Explanation:

After Line 2 is executed, numbers is [5, 7, 2]. After Line 3, the element at index 1 is deleted, making numbers [5, 2]. After Line 4, numbers becomes [5, 2, 1]. And after Line 5, the element currently at index 1 is deleted yet again, and numbers become [5, 1].

Question 3

What is the output of the following code snippet? Type Error if it results in an error.

1
2
3
4
numbers = [5, [4, 3], 2]
numbers[1].append(9)
del numbers[2]
print(numbers)

[5, [4, 3, 9]]
Explanation:

Line 2 appends 9 to the inner list [4, 3]. Line 3 deletes whatever is currently at index 2, which is 2, and numbers become [5, [4, 3, 9]].