24. List methods
You have built lists by hand and walked them with for
and enumerate. Python lists also come with built-in
methods — functions that belong to the list and do the
common jobs for you: sorting, reversing, copying, searching, counting.
Learn these and you rarely need to write the loop yourself.
This chapter uses the lists from Chapter 22.
Sorting a list:
.sort() and sorted()
.sort() reorders the list in place — it
changes the original.
scores = [30, 12, 7, 24]
scores.sort()
print(scores) # [7, 12, 24, 30]It sorts text alphabetically too:
names = ["Cara", "Ada", "Ben"]
names.sort()
print(names) # ['Ada', 'Ben', 'Cara']sorted(lst) does the same but returns a new
list, leaving the original unchanged:
scores = [30, 12, 7, 24]
ascending = sorted(scores)
print(ascending) # [7, 12, 24, 30]
print(scores) # [30, 12, 7, 24] (unchanged)Sorting your own way
Pass a key function to sort by a computed value, or
reverse=True for descending order:
scores = [30, 12, 7, 24]
scores.sort(reverse=True)
print(scores) # [30, 24, 12, 7]words = ["banana", "fig", "apple", "kiwi"]
words.sort(key=len) # sort by string length
print(words) # ['fig', 'kiwi', 'apple', 'banana']Open exercises/24/01-sort.py. A list of numbers is
provided. Sort it ascending, print it, then sort it descending and print
again.
Reversing a list:
.reverse()
.reverse() flips the list in place:
items = ["a", "b", "c"]
items.reverse()
print(items) # ['c', 'b', 'a']To get a reversed copy without changing the original, use the slice
items[::-1] or list(reversed(items)):
items = ["a", "b", "c"]
flipped = items[::-1]
print(flipped) # ['c', 'b', 'a']
print(items) # ['a', 'b', 'c'] (unchanged)Joining a list into text
", ".join(lst) glues every item into one string, the
separator between each. Items must be strings.
fruits = ["apple", "banana", "cherry"]
print(", ".join(fruits)) # apple, banana, cherry
print(" - ".join(fruits)) # apple - banana - cherry
print("".join(fruits)) # applebananacherryFor a list of numbers, convert them first:
scores = [7, 12, 24, 30]
print(" ".join(str(n) for n in scores)) # 7 12 24 30Copying a list: .copy()
.copy() returns a shallow copy — a new list with the
same items:
original = [1, 2, 3]
copy = original.copy()
copy[0] = 99
print(original) # [1, 2, 3] (unchanged)
print(copy) # [99, 2, 3]Without .copy(), assigning a list to another variable
gives you a second reference to the same list (covered in Chapter
22).
Searching: .index() and
.count()
.index(value) returns the position of the first
occurrence:
fruits = ["apple", "banana", "cherry", "banana"]
print(fruits.index("banana")) # 1It raises a ValueError if the value is not in the list.
Check with in first if you are not sure:
if "grape" in fruits:
print(fruits.index("grape"))
else:
print("not found").count(value) returns how many times a value
appears:
print(fruits.count("banana")) # 2
print(fruits.count("grape")) # 0List comprehensions
A list comprehension builds a new list from an
expression applied to each item. The syntax is
[expression for item in iterable]:
nums = [1, 2, 3, 4, 5]
doubled = [x * 2 for x in nums]
print(doubled) # [2, 4, 6, 8, 10]You can add a condition to filter items:
evens = [x for x in nums if x % 2 == 0]
print(evens) # [2, 4]This is a compact way to express what would otherwise be a loop with
.append. You do not need to use comprehensions immediately;
the loop form is equally correct. Use whichever you find clearer.
Homework
Homework files are in exercises/24/homework/.
Problem 1 — Shopping line
Open exercises/24/homework/01-shopping-line.py. A list
of item names is provided. Print it as one line separated by commas,
using join.
Problem 2 — High to low
Open exercises/24/homework/02-high-to-low.py. A list of
numbers is provided. Sort it highest to lowest, then print it with
join.
Problem 3 — Leaderboard
Open exercises/24/homework/03-leaderboard.py. A jumbled
list of player names is provided. Sort them alphabetically and print a
numbered leaderboard, one per line (1. Ada,
2. Ben, ...).
Challenge — Top three
Open exercises/24/homework/04-top-three.py. A list of
scores is provided. Sort it highest-first, then print only the top three
on one line separated by spaces. Use .sort() and
join, plus a slice to take just the first three.
Stuck or finished? Open the homework solutions page.