Lesson explanation
After this lesson, you will be able to:
append() or several items with extend().remove().pop(), using its default or a specified index.Lists are mutable, so you can change their length without rebuilding them. The most useful distinction is one item vs several items: append(value) adds one object, whereas extend(iterable) adds each value from an iterable.
Use insert(index, value) when the new item belongs before an existing position. This differs from items[index] = value, which replaces the item there.
For deletion, remove(value) searches for a matching value and deletes its first occurrence; it raises ValueError when the value is absent. pop() removes and returns the last item; pop(index) removes and returns a specific position and raises IndexError if that position is invalid. Both operations mutate the original list.
You can use these operations inside loops and conditions to maintain a queue, a checklist, or a collection of job names. Avoid chaining a mutating method into a return statement: methods such as append(), extend(), insert(), and remove() return None.
append() adds a single item. extend() takes items from another iterable one by one.
services = ["api"]
services.append("worker")
services.extend(["database", "cache"])
print(services)Output:
['api', 'worker', 'database', 'cache']Appending the whole second list instead would create a nested list element.
insert(index, value) shifts the existing items to the right.
stages = ["build", "deploy"]
stages.insert(1, "test")
print(stages)Output:
['build', 'test', 'deploy']The old second element is still present.
When a value appears twice, remove() removes only the first copy.
flags = ["ready", "retry", "ready"]
flags.remove("ready")
print(flags)Output:
['retry', 'ready']A value that does not occur would cause ValueError.
With no index, pop() removes the final item; with an index, it removes that position.
workers = ["api", "queue", "mailer"]
last_worker = workers.pop()
first_worker = workers.pop(0)
print(last_worker)
print(first_worker)
print(workers)Output:
mailer
api
['queue']Both calls change the original list, while returning the removed value.
| Need | Method |
|---|---|
| Add one item at the end | items.append(value) |
| Add every item from another iterable | items.extend(values) |
| Insert before an index | items.insert(index, value) |
| Remove first equal value | items.remove(value) |
| Remove last and return it | items.pop() |
| Remove index and return it | items.pop(index) |
items[index] = value replaces instead of shifting.pop(): pop() expects an index, not the value to search for.remove() to delete all duplicates: it removes the first matching value only.