Lists can change
Unlike strings, lists are mutable: you can change them after creating them.
Changing an item
colours = ["red", "green", "blue"]
colours[1] = "yellow"
print(colours)Output
['red', 'yellow', 'blue']
Adding items
tasks = ["wake up", "brush teeth"]
tasks.append("eat breakfast")
print(tasks)
tasks.insert(0, "alarm rings")
print(tasks)Output
['wake up', 'brush teeth', 'eat breakfast'] ['alarm rings', 'wake up', 'brush teeth', 'eat breakfast']
append(x)addsxto the end.insert(i, x)putsxat positioniand moves the rest along.
Removing items
pets = ["cat", "dog", "fish", "dog"]
pets.remove("dog")
print(pets)
last = pets.pop()
print("Removed:", last)
print(pets)
del pets[0]
print(pets)Output
['cat', 'fish', 'dog'] Removed: dog ['cat', 'fish'] ['fish']
| Method | What it does |
|---|---|
remove(x) | removes the first item equal to x |
pop() | removes the last item and gives it back to you |
pop(i) | removes the item at index i |
del list[i] | deletes the item at index i |
clear() | empties the whole list |
Common mistake:
remove("kiwi")gives an error ifkiwiisn't in the list. Check withinfirst.