After this lesson you can grow, shrink, search and reorder a list using its built-in methods. A method is a function that belongs to an object, called with a dot: items.append(5). Lists come with a handful of them, and most programs use the same few over and over.
Adding items
We will keep a to-do list for a small shop. Start with a list and add to it:
tasks = ["open shop", "count cash"]
tasks.append("restock shelves")
print(tasks)
tasks.insert(1, "turn on lights")
print(tasks)['open shop', 'count cash', 'restock shelves']
['open shop', 'turn on lights', 'count cash', 'restock shelves']append always adds at the end. insert(position, item) places the item at the given index and shifts the others along. Adding at the end is quick; inserting near the front of a very large list is slower because everything after it has to move, though for normal-sized lists you will never notice.
To add several items at once, use extend with any collection:
tasks.extend(["clean floor", "close shop"])
print(tasks)['open shop', 'turn on lights', 'count cash', 'restock shelves', 'clean floor', 'close shop']Here is the trap with append: if you give it a list, the whole list becomes one item.
nested = [1, 2]
nested.append([3, 4])
print(nested)
print(len(nested))
flat = [1, 2]
flat.extend([3, 4])
print(flat)[1, 2, [3, 4]]
3
[1, 2, 3, 4]You can also join lists with +, which makes a new list, and repeat one with *:
print([1, 2] + [3])
print([0] * 4)[1, 2, 3]
[0, 0, 0, 0]Removing items
There are three common ways, and they differ in how you point at the item.
letters = ["a", "b", "c", "b", "d"]
letters.remove("b")
print(letters)
last = letters.pop()
print(last, letters)
first = letters.pop(0)
print(first, letters)['a', 'c', 'b', 'd']
d ['a', 'c', 'b']
a ['c', 'b']remove(value) deletes the first item equal to the value. pop() removes the last item, and pop(index) removes the one at that position. Both pop forms return the item, which is useful when you want to use it. The del statement also removes by position or slice, and clear() empties everything:
numbers = [10, 20, 30, 40, 50]
del numbers[0]
print(numbers)
del numbers[1:3]
print(numbers)
numbers.clear()
print(numbers)[20, 30, 40, 50]
[20, 50]
[]Removing something that is not there is an error:
["a", "b"].remove("z")ValueError: list.remove(x): x not in listIf you are unsure, test first with if "z" in items:.
Finding and counting
index(value) tells you the position of the first match. count(value) tells you how many times a value appears.
votes = ["tea", "coffee", "tea", "juice", "tea"]
print(votes.index("coffee"))
print(votes.count("tea"))
print(votes.count("milk"))1
3
0Like remove, index raises a ValueError when the value is missing, while count happily returns 0.
Reordering
reverse() flips the list in place, and sort() puts the items in order:
ages = [31, 18, 45, 22]
ages.sort()
print(ages)
ages.reverse()
print(ages)
ages.sort(reverse=True)
print(ages)[18, 22, 31, 45]
[45, 31, 22, 18]
[45, 31, 22, 18]You will see a lot more about ordering in the sorting lesson, including sorting by a rule you choose.
Methods that return None
Notice that append, extend, insert, remove, sort, reverse and clear change the list and give nothing back. What they return is None. This leads to the most famous list bug:
data = [3, 1, 2]
data = data.sort()
print(data)NoneThe list was sorted, then the name data was pointed at the None that sort returned, and the list was lost. Call the method on its own line and keep the name:
data = [3, 1, 2]
data.sort()
print(data)
print(sorted([3, 1, 2]))[1, 2, 3]
[1, 2, 3]sorted() is a function rather than a method. It leaves the original alone and returns a new list.
A small worked example
Putting several methods together, here is a queue of customers where the first to arrive is served first:
queue = []
queue.append("Asha")
queue.append("Ben")
queue.append("Chloe")
served = queue.pop(0)
print("Serving", served)
print("Waiting:", queue)Serving Asha
Waiting: ['Ben', 'Chloe']For a real queue with many items, Python has a better tool in the standard library, but a list is fine for small jobs.
Common mistakes
- Writing
items = items.sort()oritems = items.append(x). These assignNone. Call the method on its own. - Using
appendwhen you meantextend. You end up with a list inside a list. - Removing while looping. Calling
removeinside aforloop over the same list skips items. Build a new list instead. - Expecting
removeto delete every match. It removes only the first one. - Calling
popon an empty list. It raises anIndexError. Checkif items:first.
Exercise
Start with cart = ["pen", "book"]. Add "bag" to the end, put "ruler" at the front, remove "book", then print the cart and its length.
Show one possible answer
cart = ["pen", "book"]
cart.append("bag")
cart.insert(0, "ruler")
cart.remove("book")
print(cart)
print(len(cart))['ruler', 'pen', 'bag']
3Previous: Lists. Next: Tuples, a collection that cannot be changed.
Key points
- append adds one item at the end, extend adds every item of another collection, and insert adds at a chosen position.
- remove deletes the first item with a given value, pop deletes by position and hands the item back, and clear empties the list.
- index finds a position and count counts matches. index raises ValueError when the value is missing.
- Methods that change a list in place, such as append, sort and reverse, return None. Do not write items = items.sort().