Add and Remove Items in a Python List
Add an Item with append()
append() adds one item to the end of a list. You write it after the list's name, with a dot: cart.append("eggs"). A function that belongs to a value like this is called a method.
Think of joining a queue: the new person always goes to the back.
cart = ["milk", "bread"]
cart.append("eggs")
print(cart)
print(len(cart))['milk', 'bread', 'eggs'] 3
The rules
list.append(item)adds the item at the end.- It changes the list itself. You don't need
cart = ...in front. - It adds one item at a time.
Start empty, then fill up
The empty list from topic 1 is the usual starting point. Make it first, then append:
guests = []
guests.append("Sunny")
guests.append("Rocky")
print(guests)['Sunny', 'Rocky']
It works with input() from chapter 7, too. Each input() reads one line, and append() stores it:
todo = []
todo.append(input())
todo.append(input())
print(todo)['study', 'play']
Avoid: storing what append() gives back
cart = ["milk"]
cart = cart.append("eggs")
print(cart)None
The list is gone! append() changes the list and gives back None, the "no value" from chapter 5. Then cart = ... stores that None. Write cart.append("eggs") on its own line.
Avoid: two items in one append()
cart = ["milk"]
cart.append("eggs", "jam")TypeError: list.append() takes exactly one argument (2 given)
An argument is a value you put in the brackets. append() takes exactly one. To add two items, call it twice.
list.append(item)adds one item to the end of the list.