Learn Python · lesson 27 of 60 · about 7 minutes
Looping and Sorting Lists
Put the week's nights in order: build a list of numbers in a loop, sort it with sorted(), and pick the middle night.
What you'll learn
- Loop over a list
- Sort with sort() and sorted()
- Use sum(), min() and max() on lists
The week in order
The nights of sleep are still a string of digits. A loop turns them into a list of numbers, one append at a time, and sorted() puts them in order from the shortest night to the longest. The night in the middle of the sorted list gives a fairer picture of the week than the best one.
Looping over a list
A for loop visits each item in a list in order, just like the characters of a string. Built-ins like sum(), min() and max() also work on whole lists.
Looping and summarising
prices = [3, 8, 5]
for p in prices:
print(f"£{p}")
print(sum(prices), min(prices), max(prices))Output
£3
£8
£5
16 3 8Step through it: a list built one item at a time
night_hours = []
for h in "867":
night_hours.append(int(h))
print(sorted(night_hours))Output
[6, 7, 8]sort() vs sorted()
list.sort()sorts the list itself and gives back nothingsorted(list)gives you a new sorted list and leaves the original alone
Add reverse=True to either for biggest-first.
Two ways to sort
nums = [4, 1, 3]
print(sorted(nums))
print(nums)
nums.sort(reverse=True)
print(nums)Output
[1, 3, 4]
[4, 1, 3]
[4, 3, 1]Tip
A common mistake: nums = nums.sort() sets nums to None, because sort() returns nothing. Use sorted() when you want a value back.
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.