Working with lists · Python from Zero
How do you answer questions about a whole list: biggest, average, which ones match?
Course contentsWhy you need it
Once data is in a list, the real work is asking questions about it. Python has built-in helpers (sum, max, min, sorted) and you can write your own with the patterns you know: loop + condition + accumulator, or loop + condition + append to build a new list (filtering).
The intuition
| Helper | Gives |
|---|---|
sum(xs) | total |
max(xs), min(xs) | largest, smallest |
len(xs) | how many |
sorted(xs) | a new sorted list |
x in xs | True if x is in the list |
Average = sum(xs) / len(xs).
Filtering means "keep only the items that pass a test":
passed = []
for s in scores:
if s >= 50:
passed.append(s)Knowing how to write max yourself (keep the best so far, replace it when you find a better one) is a classic interview warm-up.
Definition
Filtering
Filtering builds a new list containing only the items of another list that satisfy a condition.
Built-in function
A built-in function, such as sum, max or sorted, is always available in Python without importing anything.
Examples
Temperature report
Try it yourselfBuilt-ins first, then a filter.
temps = [21, 25, 19, 30, 24]
print(max(temps), min(temps))
print(sum(temps) / len(temps))
hot = []
for t in temps:
if t >= 24:
hot.append(t)
print(hot)- L2Largest and smallest.
30 19 - L3Average: 119 / 5.
23.8 - L6Each t is tested; only 25, 30 and 24 pass.
- L8The filtered list keeps the original order.
[25, 30, 24]
Max by hand
Try it yourselfThe same idea that max() uses inside.
words = ["cat", "elephant", "dog"]
longest = words[0]
for w in words:
if len(w) > len(longest):
longest = w
print(longest)
print(sorted(words))- L2The best so far: the first word.
longest = 'cat' - L4elephant is longer than cat: replace.
longest = 'elephant' - L4dog is not longer: keep elephant.
- L7sorted gives alphabetical order and doesn't change words.
['cat', 'dog', 'elephant']
Common mistakes
Average of an empty list
sum([]) / len([]) divides by zero. Check if len(xs) > 0: first.
sorted() vs .sort()
sorted(xs) returns a new list; xs.sort() changes xs and returns None. Don't write xs = xs.sort().
Quick quiz
1. What does this print?
print(sorted([3, 1, 2])[0], max([3, 1, 2]))Show the answer
Answer: A
sorted gives [1, 2, 3], whose first item is 1; the max is 3.
2. What does this print?
a = [1, 2, 3, 4]
b = []
for x in a:
if x % 2 == 0:
b.append(x * 10)
print(b)Show the answer
Answer: A
Only the even numbers 2 and 4 pass, and each is multiplied by 10.
Practice
3 exercises in three steps: predict what a program prints, change a program to meet a new requirement, then write one from scratch. Your code runs in the browser and is checked the moment you submit.
- PredictReport card
Type exactly what this program prints.
- ModifyMore statistics
The program prints the passing scores. Also print, on the next two lines, how many scores failed (below 50) and the highest score.
- WriteAbove average
Read n, then n whole numbers. Print a list of the numbers that are strictly above the average, in their original order.
Practise this lesson
Open the interactive lesson to edit and run these examples and solve the exercises with instant feedback. Free to start, no sign-up.
Interactive lessons open in order. If you have not done the earlier ones yet, you start at the course map.
Terms in this lesson
| Term | Chinese | Definition |
|---|---|---|
| Filtering | 筛选 | Building a new list with only the items that pass a test. |
| Built-in function | 内置函数 | A function such as sum or max that Python provides without imports. |
| sorted() | sorted() 排序函数 | A built-in that returns a new list with the items in ascending order. |
| Average | 平均值 | The sum of the values divided by how many there are. |