4. Lists
4.5 Loop, sort and summarise
Highlights & notes
Select lesson text to highlight it, or tap Add note.
Bookmarks
Bookmark a lesson to see it here.
Use a for loop to work on each item. Python also has quick built-ins for numbers: sum, min, max.
To sort, sorted(list) gives a new sorted list; list.sort() sorts the list itself. Add reverse=True for largest first.
Example
amounts = [250, 1200, 75, 640]
for a in amounts:
print(a * 2)
print(sum(amounts), min(amounts), max(amounts))
print(sorted(amounts))
print(sorted(amounts, reverse=True))500 2400 150 1280 2165 75 1200 [75, 250, 640, 1200] [1200, 640, 250, 75]
sorted() leaves the original list unchanged. .sort() changes it and returns None.
Practice in Python ✓ Solved
Print each order amount with GST added (multiply by 1.18, rounded to 2 places). Then print the total of the original amounts.
Expected output
118.0 295.0 47.2 390
Reference solution
orders = [100, 250, 40]
for amount in orders:
print(round(amount * 1.18, 2))
print(sum(orders))
Question 1 · Easy
What does sum([2, 3, 5]) give?
Question 2 · Medium
x = [3, 1, 2]; y = sorted(x). What is x now?
Question 3 · Hard
x = [3, 1, 2]; y = x.sort(). What is y?
Key takeaways
Loop with for. sum/min/max summarise numbers. sorted() returns a new list; .sort() changes the list.
Save your progress
Start free and your progress, code and notes stay saved. Free for 1 month, no card needed.
Start free Log in