24. List methods — Homework solutions
The .py solution files are in
exercises/24/homework/solutions/.
Problem 1 — Shopping line
Problem. Print a list of names on one comma-separated line.
Worked solution.
items = ["milk", "bread", "eggs", "apples"]
print(", ".join(items))Output:
milk, bread, eggs, apples
Common mistakes.
- Building the line by hand with a loop and string concatenation. It
works, but
joinis the one-line tool for this. - Calling
joinbackwards:items.join(", "). The separator string is the object you call.joinon, not the list.
Problem 2 — High to low
Problem. Sort numbers from highest to lowest, then print them.
How to think about it. Call
.sort(reverse=True) to get descending order, then
join with a space separator. join requires
strings, so convert each number with str.
Worked solution.
nums = [30, 12, 7, 24]
nums.sort(reverse=True)
print(" ".join(str(n) for n in nums))Output:
30 24 12 7
Common mistakes.
- Calling
.sort()withoutreverse=True, which gives ascending order. - Forgetting to convert numbers to strings before
join, which raises aTypeError.
Problem 3 — Leaderboard
Problem. Sort names alphabetically and print a numbered list.
How to think about it. .sort() with no
arguments sorts text alphabetically. Then walk it with
enumerate(players, 1), printing position and name.
Worked solution.
players = ["Ben", "Ada", "Cara", "Dan"]
players.sort()
for i, name in enumerate(players, 1):
print(f"{i}. {name}")Output:
1. Ada
2. Ben
3. Cara
4. Dan
Challenge — Top three
Problem. Sort highest-first and print the top three.
How to think about it. Sort descending, then take a
slice of the first three elements and join them.
Worked solution.
scores = [30, 12, 45, 7, 24, 50]
scores.sort(reverse=True)
top = scores[:3]
print(" ".join(str(n) for n in top))Output:
50 45 30
Common mistakes.
- Printing
str(scores[0]) + str(scores[1]) + str(scores[2])with no spaces, giving504530. Usejoinwith" ". - Using
scores[0:3]instead ofscores[:3]. Both work; the shorter form is conventional.
Done?
You now have Python's most useful list tools: .sort(),
sorted(), .reverse(), join,
.copy(), .index(), .count(), and
a taste of list comprehensions. The last chapter of Part 5 —
Modules and import — shows how to split a program
across files.