Python List Methods
Lists have a set of built-in methods for adding, removing, searching and ordering items. Unlike string methods, most list methods modify the list in place and return None.
Overview
| Method | What it does |
|---|---|
append(x) |
Add x to the end |
extend(iterable) |
Add every item from another iterable |
insert(i, x) |
Insert x before position i |
remove(x) |
Remove the first item equal to x |
pop([i]) |
Remove and return the item at i (last by default) |
clear() |
Remove all items |
index(x) |
Position of the first x |
count(x) |
How many times x appears |
sort() |
Sort the list in place |
reverse() |
Reverse the list in place |
copy() |
Return a shallow copy |
Adding items
queue = ["Ann", "Binh"]
queue.append("Chi")
print(queue)
queue.insert(0, "VIP")
print(queue)
queue.extend(["Dung", "Em"])
print(queue)['Ann', 'Binh', 'Chi']
['VIP', 'Ann', 'Binh', 'Chi']
['VIP', 'Ann', 'Binh', 'Chi', 'Dung', 'Em']
A frequent mistake is using append when you meant extend: append([1, 2]) adds one item, the list [1, 2].
a = [0]
a.append([1, 2])
b = [0]
b.extend([1, 2])
print(a, b)[0, [1, 2]] [0, 1, 2]
Removing items
stack = ["a", "b", "c", "d", "b"]
stack.remove("b") # first matching value
print(stack)
last = stack.pop() # remove and return the last item
print(last, stack)
first = stack.pop(0) # remove and return by index
print(first, stack)
del stack[0] # the del statement also works
print(stack)
stack.clear()
print(stack)['a', 'c', 'd', 'b']
b ['a', 'c', 'd']
a ['c', 'd']
['d']
[]
remove() raises ValueError if the value isn't present, and pop() raises IndexError on an empty list — check with in or if stack: first.
Sorting
sort() orders the list in place. sorted() is a built-in function that leaves the original alone and returns a new sorted list.
scores = [70, 95, 82, 61]
scores.sort()
print(scores)
scores.sort(reverse=True)
print(scores)
names = ["bob", "Alice", "carol", "Dave"]
print(sorted(names)) # uppercase sorts before lowercase
print(sorted(names, key=str.lower)) # case-insensitive
print(sorted(names, key=len)) # by length (ties keep their order)
print(names) # unchanged[61, 70, 82, 95]
[95, 82, 70, 61]
['Alice', 'Dave', 'bob', 'carol']
['Alice', 'bob', 'carol', 'Dave']
['bob', 'Dave', 'Alice', 'carol']
['bob', 'Alice', 'carol', 'Dave']
The key argument takes a function that is applied to each item to decide its sort position. Python's sort is stable, which means items with equal keys stay in their original order.
Sorting records
key really shines with structured data:
people = [("Hoa", 31), ("An", 25), ("Quang", 40)]
by_age = sorted(people, key=lambda p: p[1])
print(by_age)
oldest = max(people, key=lambda p: p[1])
print(oldest[0])[('An', 25), ('Hoa', 31), ('Quang', 40)]
Quang
Searching and counting
votes = ["yes", "no", "yes", "yes", "abstain"]
print(votes.count("yes"))
print(votes.index("no"))
print("maybe" in votes)
votes.reverse()
print(votes)3
1
False
['abstain', 'yes', 'yes', 'no', 'yes']
Tip: A very common bug:
numbers = numbers.sort(). Becausesort()returnsNone, this throws away your list. Either callnumbers.sort()on its own line, or usenumbers = sorted(numbers).
Test yourself
What does pop() return?
- Nothing (None)
- The removed item
- The new length
- The remaining list
What is the difference between list.sort() and sorted(list)?
- No difference
sort()changes the list in place and returns None;sorted()returns a new listsorted()only works on numberssort()returns a new list
After x = [1]; x.append([2, 3]), what is len(x)?
- 1
- 2
- 3
- 4