Changing a List

Challenge 3-1: Arrays

Now, what if we want to add something to a list? Or what if we want to change what's stored at a particular place in the list? Thankfully, Python makes both of these operations really easy.

If you want to change what's stored at a certain index in a list, you can just use the assignment operator = (remember, we've used this before to assign values to a variable).

In the case of a list, you first need to access the element you want to change by using its index, then assign it a new value.

>>> fruit = ["apple", "banana", "grape"]
>>> fruit[1]
'banana'
>>> fruit[1] = "orange"
>>> fruit
['apple', 'orange', 'grape']

So by using the index 1, we've changed the second element in the list from "banana" to "orange".

Adding an element to a list is almost as easy. Python has a built-in function called .append that only works on lists. .append works by adding an item to the end of the list - which is actually the only way we can add items to a list, we can't insert them into the middle.

Here's an example of how .append can be used. Be really careful to note that, unlike some other functions we've seen, this one comes after the list that we're changing.

>>> numbers = [1, 2, 3]
>>> numbers
[1, 2, 3]
>>> numbers.append(4)
>>> numbers
[1, 2, 3, 4]

Here we put the .append function after the list we're adding to, and then in the brackets we put the thing we wanted to add to the list. Appending can work with anything that could normally appear in a list - numbers, strings, floats or variables.

>>> numbers.append("hello")

>>> numbers.append(5.7)
>>> numbers

[1, 2, 3, 4, 'hello', 5.7]

Note as well that as we use more and more appends, the new values keep appearing at the end of the list.