Python Add & Remove List Items
List add and remove methods add items to a list and take items out of a list. insert() adds an item in the middle.
Add at the end with append()
tasks = ["read", "write"]
tasks.append("draw")
print(tasks)Add many with extend()
tasks = ["read"]
tasks.extend(["write", "draw"])
print(tasks)Remove by value with remove()
Only the first matching item is removed. The second "read" stays.
tasks = ["read", "write", "read"]
tasks.remove("read")
print(tasks)Remove by index with pop()
pop() hands the removed item back. You can save it in a variable.
tasks = ["read", "write", "draw"]
done = tasks.pop(1)
print(done)
print(tasks)Delete with del
del removes an item by index. Nothing is given back.
tasks = ["read", "write", "draw"]
del tasks[0]
print(tasks)Empty the list with clear()
tasks = ["read", "write"]
tasks.clear()
print(tasks)Example
todo = ["wake up", "brush teeth"]
print(todo)
todo.append("make breakfast")
print(todo)
todo.extend(["pack bag", "catch bus"])
print(todo)
todo.remove("brush teeth")
print(todo)
done = todo.pop(0)
print("Done:", done)
print(todo)Key points
- Use append(item) to add one item at the end of a list
- Use extend(list) to add every item from another list
- Use remove(value) to delete the first item that matches a value
- Use pop(index) to remove an item by index
- It gives the removed item back to you.
- Use clear() to empty a list
- The list itself still exists.
- Use del my_list[index] to delete an item by index, with nothing given back
- These methods change which items a list holds.
- Check with in first when you are not sure.
- Each method does a single clear job.
In this example, the to-do list starts with two tasks. append() adds make breakfast at the end. extend() adds two more tasks from a second list. remove() deletes brush teeth by its value. Then pop(0) removes the first task and saves it in done. The last two prints show the finished task and the shorter list.
Note
remove() stops with a ValueError if the value is not in the list.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does this code print? fruits = ["apple", "banana"] fruits.append("cherry") print(fruits)