Python List Methods
Lists come with methods for adding, removing, searching and ordering their items. Unlike string methods, most list methods change the list itself and return None. This is an important difference: names.sort() sorts the list in place, so writing names = names.sort() would replace your list with None.
Adding items
basket = ["rice", "milk"]
basket.append("eggs") # one item at the end
basket.insert(0, "bread") # at a position
basket.extend(["tea", "sugar"]) # all items of another list
print(basket)
print(len(basket))['bread', 'rice', 'milk', 'eggs', 'tea', 'sugar'] 6
append adds its argument as one item. Appending a list would put the whole list inside as a single item; extend adds the items one by one, as does basket += ["tea", "sugar"].
Removing items
basket = ["bread", "rice", "milk", "eggs", "milk"]
basket.remove("milk") # the first "milk"
last = basket.pop() # take out the last item
first = basket.pop(0) # take out the item at index 0
print(basket, last, first)
del basket[0]
print(basket)
basket.clear()
print(basket)['rice', 'eggs'] milk bread ['eggs'] []
remove deletes the first item equal to its argument, and raises a ValueError if there is none, so check with in first when you are not sure. pop removes an item and gives it back, which is useful when you process items one by one.
Searching and counting
votes = ["yes", "no", "yes", "yes", "maybe"]
print(votes.count("yes"))
print(votes.index("no"))
print("maybe" in votes)3 1 True
Sorting
sort puts the items in order, and reverse=True turns the order round. The key argument sorts by a value worked out for each item, for example the length of each word:
nums = [42, 7, 19, 3]
nums.sort()
print(nums)
nums.sort(reverse=True)
print(nums)
words = ["banana", "fig", "cherry", "kiwi"]
words.sort(key=len)
print(words)
words.reverse()
print(words)
print(sorted("python"))[3, 7, 19, 42] [42, 19, 7, 3] ['fig', 'kiwi', 'banana', 'cherry'] ['cherry', 'banana', 'kiwi', 'fig'] ['h', 'n', 'o', 'p', 't', 'y']
sorted is the function version: it returns a new sorted list and leaves the original as it was, and it works on any collection, even a string. Sorting is stable: items with equal keys, such as fig and kiwi above, keep their original order.
Practice exercises
- Start with an empty to-do list, add three tasks, insert a task at the front, and print the list.
- Remove a task by name, then take out the last task with
popand print it. - Sort a list of names alphabetically, then by length, longest first.
- Count how many times each of the numbers 1, 2 and 3 appears in
[1, 3, 2, 3, 3, 1].