List methods
- Python course
- Beginner
- Lesson 55/116
- 3 min
Learn append, extend, insert, pop, remove methods.
List methods
Common list methods: append adds to the end, insert adds at an index, remove removes an item, pop removes the last item.
cart = ["Apple"]
cart.append("Bread") # ['Apple', 'Bread']
cart.insert(0, "Milk") # ['Milk', 'Apple', 'Bread']
cart.remove("Apple") # ['Milk', 'Bread']
cart.pop() # ['Milk']These methods modify the list in place; they do not return a new list.
pop and len
pop removes and returns the last item. len gives the list length:
cart = ["Apple", "Bread", "Milk"]
last = cart.pop() # 'Milk', cart: ['Apple', 'Bread']
n = len(cart) # 2pop can take an index too: cart.pop(0) removes the first item. len gives 0 for an empty list.
Practice Modify with methods
Assign cart = ["Apple"]. Add cart.append("Bread"). Add cart.insert(0, "Milk"). Print print(cart).
Starter code
# List methodsSample solution
cart = ["Apple"]
cart.append("Bread")
cart.insert(0, "Milk")
print(cart)Expected output
['Milk', 'Apple', 'Bread']
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does cart.insert(0, "Milk") do?
- Removes Milk from the cart
- Adds Milk at the start Correct answer
- Empties the cart
- Finds Milk
Explanation: insert(0, ...) adds the item at the start (index 0).
2 Complete the remove call
cart = ["Apple", "Bread"]
cart.____("Apple")
cart = ["Apple", "Bread"]
cart.remove("Apple")
Explanation: remove removes the item from the list.
3 Match the methods
| Term | Meaning |
|---|---|
append |
Add to end |
insert |
Add at index |
remove |
Remove item |
pop |
Remove last |