Python Arena
Step 5 of 6

max, min, sum and methods versus functions

Python has functions for the most common questions about a list of numbers. max returns the greatest item, min the smallest and sum the sum of all the items:

sales = [120, 75, 210, 95]
print("Best day:", max(sales))
print("Worst day:", min(sales))
print("Total:", sum(sales))
print("Average:", sum(sales) / len(sales))
Output
Best day: 210
Worst day: 75
Total: 500
Average: 125.0

The average is the sum divided by the number of items. max and min work for strings too: then they give the alphabetically last and first item.

Methods and functions

You now know two kinds of commands that work with lists, and they are written differently:

  • methods are written after the list, with a dot: sales.append(80), sales.sort(), sales.pop(). Most of them change the list.
  • functions get the list as an argument, in the parentheses: len(sales), max(sales), sum(sales), sorted(sales). They return a value and leave the list as it is.
sales = [120, 75, 210]
sales.append(95)
sales.sort()
print(sales)
print(len(sales), max(sales), sorted(sales))
Output
[75, 95, 120, 210]
4 210 [75, 95, 120, 210]

Mixing the two up is a common slip, and Python tells you so. There is no max method:

sales = [120, 75, 210]
print(sales.max())
Python stops with
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(sales.max())
          ^^^^^^^^^
AttributeError: 'list' object has no attribute 'max'

and no sort function:

sales = [120, 75, 210]
sort(sales)
Python stops with
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    sort(sales)
    ^^^^
NameError: name 'sort' is not defined. Did you mean: 'sorted'?

An AttributeError about a 'list' object means you wrote a function as a method; a NameError means you wrote a method as a function.

An empty list has no greatest or smallest item, so max([]) and min([]) stop with a ValueError. sum([]) is 0.

Your task

Challenge 1 of 3

Fill in the blanks so the program prints the total, the highest and the lowest of the step counts:

Total: 31200
Highest: 9800
Lowest: 3100

Challenge 2

Write a program that reads temperatures (whole numbers) until the user types an empty line, and then prints how many there were, the warmest, the coldest and the average:

Temperature: 18
Temperature: 23
Temperature: 16
Temperature:
Readings: 3
Warmest: 23
Coldest: 16
Average: 19.0

You can assume the user types at least one temperature.

Challenge 3

What does this program print? Type each line it prints.