Learn Python · lesson 26 of 60 · about 7 minutes
Adding, Removing and Slicing
Keep a shopping list: grow it with append(), cross things off with remove(), and show the first items with a slice.
What you'll learn
- Add items with append() and insert()
- Remove items with remove() and pop()
- Slice lists
The shopping list
Sam's shopping list starts with milk, bread and eggs. The assistant asks for one thing to add, which goes on the end with append, and one thing Sam already has, which comes off with remove. remove crashes if the item isn't there, so the code checks with in first. ", ".join(shopping) turns the list into one line of text.
Growing a list
append(x)adds x to the endinsert(i, x)puts x at position i, shifting the rest along
append and insert
queue = ["Ada", "Bo"]
queue.append("Cy")
queue.insert(0, "Zed")
print(queue)Output
['Zed', 'Ada', 'Bo', 'Cy']Shrinking a list
remove(x)deletes the first item equal to xpop()removes the last item and gives it back to you (pop(i)removes at index i)
remove and pop
stack = [1, 2, 3, 2]
stack.remove(2)
top = stack.pop()
print(stack, top)Output
[1, 3] 2Slices work on lists too
nums = [10, 20, 30, 40, 50]
print(nums[1:3])
print(nums[:2])
print(nums[-2:])Output
[20, 30]
[10, 20]
[40, 50]Checking first, and joining
shopping = ["milk", "bread"]
if "cheese" in shopping:
shopping.remove("cheese")
print(", ".join(shopping))Output
milk, breadNow try it yourself
This lesson is free in Codiqo, with 11 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.