Last time, we saw how to change existing items in a list using their index, like colors[1] = "yellow"
.
But what if you want to add a new item to the list without replacing an existing one?
Engagement Message
How might you add to the collection?
Python lists have a special built-in function (called a method) just for this: .append()
.
This method adds the specified item to the very end of the list. The list grows by one item.
Engagement Message
With me so far?
Here's how you use it: list_name.append(new_item)
.
If we have tasks = ["review code"]
, and we run tasks.append("write tests")
, the list changes.
Engagement Message
How long do you think the list will be after this operation?
After running the operation the tasks
list becomes ["review code", "write tests"]
. The new item "write tests"
is added at the end.
You can append items of any data type (strings, numbers, Booleans) to a list.
Engagement Message
Do you think you can append a list to a list?
