Loading...
Loading...
Add, remove, and modify items in lists
Lists aren't static — you can add items, remove items, sort, reverse, and more. These actions are called methods — functions that belong to a list.
tasks = ["buy groceries", "do laundry"]
tasks.append("wash dishes") # Add to end
tasks.insert(0, "pay bills") # Insert at position 0
tasks.remove("do laundry") # Remove by value
popped = tasks.pop() # Remove and return last item
tasks.sort() # Sort alphabetically
tasks.reverse() # Reverse the order
print(tasks)fruits = ["apple", "banana"]
fruits.append("cherry") # ["apple", "banana", "cherry"]
fruits.insert(1, "kiwi") # ["apple", "kiwi", "banana", "cherry"]| Method | What it does | Example |
|---|---|---|
| `append(item)` | Adds item to the end | `list.append(5)` |
| `insert(i, item)` | Adds item at position i | `list.insert(0, x)` |
| `extend([a, b])` | Adds multiple items | `list.extend([1, 2])` |
fruits = ["apple", "banana", "cherry", "banana"]
fruits.remove("banana") # Removes FIRST "banana": ["apple", "cherry", "banana"]
last = fruits.pop() # Removes and returns "banana": ["apple", "cherry"]
first = fruits.pop(0) # Removes and returns "apple": ["cherry"]| Method | What it does |
|---|---|
| `remove(value)` | Removes the first occurrence of value |
| `pop(index)` | Removes and returns item at index (default: last) |
| `clear()` | Removes ALL items, leaving an empty list |
nums = [3, 1, 4, 1, 5, 9]
print(nums.index(4)) # 2 — position of value 4
print(nums.count(1)) # 2 — how many times 1 appears
nums.sort() # [1, 1, 3, 4, 5, 9]
nums.reverse() # [9, 5, 4, 3, 1, 1]Lists that never change are called tuples (covered later). But most real lists need updating:
| ❌ Wrong | Why | ✅ Right |
|---|---|---|
| `result = list.sort()` | `sort()` returns None! It modifies in place | `list.sort()` then use `list` |
| `fruits.remove(0)` | `remove` removes by VALUE, not index | `fruits.pop(0)` to remove by index |
| `fruits.append("apple", "banana")` | `append` adds ONE item | `fruits.extend(["apple", "banana"])` |
Start with a list: numbers = [5, 2, 8, 1, 9]. Then:
numbers = [5, 2, 8, 1, 9] numbers.append(3) numbers.insert(2, 7) numbers.sort() numbers.pop(0) print(numbers)