Everyone Can Learn Program
中文 Start learning
Course 2 · Python BasicsLesson 12 of 14Free to read

Working with lists · Python from Zero

How do you answer questions about a whole list: biggest, average, which ones match?

Course contents

Why 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

HelperGives
sum(xs)total
max(xs), min(xs)largest, smallest
len(xs)how many
sorted(xs)a new sorted list
x in xsTrue 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 yourself

Built-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)
Step by step
  1. L2Largest and smallest.30 19
  2. L3Average: 119 / 5.23.8
  3. L6Each t is tested; only 25, 30 and 24 pass.
  4. L8The filtered list keeps the original order.[25, 30, 24]

Max by hand

Try it yourself

The 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))
Step by step
  1. L2The best so far: the first word.longest = 'cat'
  2. L4elephant is longer than cat: replace.longest = 'elephant'
  3. L4dog is not longer: keep elephant.
  4. 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]))
  1. A
    1 3
  2. B
    3 3
  3. C
    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)
  1. A
    [20, 40]
  2. B
    [10, 30]
  3. C
    [2, 4]
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.

  1. PredictReport card

    Type exactly what this program prints.

  2. 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.

  3. 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

TermChineseDefinition
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.