Modifying Lists in Python
In this lesson, you will learn about various methods for updating lists and understand the concept of list mutability.
Let's say you're planning a trip to the grocery store, and you create a list of items you need to buy:
Imagine your partner wants you to specifically buy green apples and asks you to update the list.
To update the string 'apple', we first need to identify its index in the list.
The thrid element 'apple' is at index 2 (remember, indices start from 0).
If you don't want to manually find the index, you can also use the list.index()
method to get the index:
Once you identified the index, you can use it to update the corresponding element in the list.
Note that we did not create a new list with updated values. Instead, we directly modified the existing list.
This is called mutability.
Remember, in contrast, strings are immutable, meaning they cannot be changed.
If you want to update a string, you have to create a new one with the updated values. For example:
Back to our shopping list example.
Looking at your list, you realize that you should switch the order of eggs and bread because you will stop at the bakery first.
We can use slicing to update a sequence of elements in the list.
Note that you don't have to assign the same number of elements again.
For example here, instead of just replacing the first and second elements, we can also add an additional grocery item:
Now imagine you forgot to add chocolate to your list.
You add an element to a list using the list.append(value)
method:
To extend the list with multiple elements at once, use the list.extend(new_list)
method:
Now, you also want to add bananas to your shopping list. You want to place them next to the apples because you will find both in the fruit section of the supermarket.
To add an element at a specific position, you can use the list.insert(index, value)
method:
Then, you are in the store and have filled your cart with the first items on your list. And you want to keep your list up-to-date.
There are two methods to remove elements from a list.
list.remove(value)
removes the first occurence of a specified value:
list.pop(index)
removes an element at a specified position:
If you don't specify an index, the last element is removed:
You can also remove elements from a list using slicing:
That's it for now. We've covered many new methods.
Let's see if you remember them...
What will be the output?
What will be the output?
What will be the output?
What will be the output?
What will be the output?
What will be the output?
What will be the output?
What will be the output?
What will be the output?
What will be the output?
What will be the output?