List Methods
Lists come with built-in methods, functions you call with a dot such as items.append("milk"), for adding, removing, searching and sorting items. Knowing them well, and knowing which ones change the list and which ones return something, is key to writing correct code.
Adding items
append(x)adds one item to the end.insert(i, x)inserts an item at positioni, shifting the others right.extend(iterable)adds every item from another list (or other sequence) to the end.
items = ["sugar", "bread"]
items.append("milk")
print(items)
items.insert(0, "tea leaves")
print(items)
items.extend(["eggs", "flour"])
print(items)
Using append() when you mean extend(). append() adds its argument as a single item, even if it is a whole list.
a = [1, 2] a.append([3, 4]) print(a) b = [1, 2] b.extend([3, 4]) print(b)
Removing items
remove(x)deletes the first item equal tox.pop()removes and returns the last item;pop(i)does the same for positioni.clear()empties the whole list.
items = ["tea leaves", "sugar", "bread", "milk", "eggs", "flour"]
items.remove("bread")
print(items)
last = items.pop()
print(last, items)
first = items.pop(0)
print(first, items)
items.clear()
print(items)
Removing something that isn't there. items.remove("rice") raises ValueError: list.remove(x): x not in list, and pop() on an empty list raises IndexError. Check first with if "rice" in items:.
Which one should you use? Choose remove() when you know the value you want gone, pop() when you know the position and also want the item back, and the del statement (as in del items[0]) when you know the position but don't need the item. del also accepts slices, so del items[:2] removes the first two items at once.
Searching
index(x)returns the position of the first item equal tox(and raisesValueErrorif there is none).count(x)returns how many timesxappears.
rolls = [3, 7, 3, 9, 3] print(rolls.count(3)) print(rolls.index(9)) print(rolls.index(3)) # only the first match
Sorting and reversing
sort() arranges the list in place, smallest first. Pass reverse=True for largest first. reverse() simply flips the current order.
scores = [64, 90, 72, 85] scores.sort() print(scores) scores.sort(reverse=True) print(scores) days = ["Mon", "Tue", "Wed"] days.reverse() print(days)
sort() vs. sorted()
The built-in function sorted() returns a new sorted list and leaves the original alone. Both accept a key argument: a function applied to each item to decide its sort order.
names = ["Wanjiru", "abdi", "Brian"] print(sorted(names)) print(sorted(names, key=str.lower)) print(names) rides = ["matatu", "boda", "tuk-tuk", "bus"] print(sorted(rides, key=len))
By default, capital letters sort before lowercase ones, so "abdi" lands last. key=str.lower compares lowercase versions instead, giving a natural alphabetical order. key=len sorts by length. You can write your own key functions with lambda.
Methods that change a list in place, such as sort(), append(), reverse() and remove(), return None. Writing scores = scores.sort() throws your list away!
scores = [64, 90, 72] result = scores.sort() print(result) print(scores)
Copying
copy() returns a new list with the same items, so changes to the copy don't affect the original. See the aliasing trap on Lists.
Quick reference
| Method | What it does | Returns |
|---|---|---|
append(x) | Adds x to the end | None |
insert(i, x) | Inserts x at position i | None |
extend(seq) | Adds every item of seq | None |
remove(x) | Deletes the first x | None |
pop(i) | Removes the item at i (default: last) | The removed item |
clear() | Removes everything | None |
index(x) | Finds the first x | Its position |
count(x) | Counts occurrences of x | A number |
sort() | Sorts in place | None |
reverse() | Reverses in place | None |
copy() | Makes a shallow copy | A new list |
A small worked example
queue = [] # customers at an M-Pesa agent
queue.append("Otieno")
queue.append("Njeri")
queue.append("Hassan")
served = queue.pop(0) # first come, first served
print("Now serving:", served)
print("Still waiting:", queue)
print("Njeri is number", queue.index("Njeri") + 1, "in line")
Key points
- Add with
append(),insert()andextend(); remove withremove(),pop()andclear(). index()andcount()search a list; missing items raiseValueError.sort()changes the list;sorted()returns a new one. Both acceptkeyandreverse.- In-place methods return
None, so never assign their result back to the list.
Tip: use the ← and → keys to move between pages.
