Lesson 6
Dealing with Sequences of Objects
Chapter 3: More on lists
Adding to and deleting from list
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.
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!