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))
Best day: 210
Worst day: 75
Total: 500
Average: 125.0The 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))
[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())
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)
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.