Adding Items to a List
The list page introduced lists and showed how to create them and print the list and values in it. This page looks at how to add to a list. There are two ways to add a value to a list:
You can either append it to the end of the list, or use insert to add a value to a particular place in the list using the index numbers.
Appending
- toys = ["car","lego","barbie"]
- toys.append("robot")
This would add "robot" to the end of the toys list. Note the way the command is used : listname.append(object to be added) The list would now be ["car","lego","barbie","robot"]
Inserting
- toys = ["car","lego","barbie","robot"]
- toys.insert(1,"teddy")
The number inside the bracket (the 1 in this case) states the index you want to add the value into. So this would add "teddy" to index 1. The list would now be ["car","teddy",lego","barbie","robot"] .