max
does its work by applying the
>
operator to the items in the
list
.
You can actually see this
>
(“Python greater than”)
in
line
1709
of the source code
for
max
,
which is written in the language C.
When you apply the
>
operator to two
int
s,
it tells you which
int
is bigger.
""" Find the max (in order of increasing value) of a list of ints. """ import sys numbers = [10, 20, 50, 40, 30] try: m = max(numbers) except ValueError: print("Can't take the max of an empty list.", file = sys.stderr) sys.exit(1) print(f"m = {m}") sys.exit(0)
m = 50
When you apply the
>
operator to two
str
ings,
it tells you which
string
comes later in alphabetical order.
""" Find the max (in alphabetical order) of a list of strings. """ import sys months = ["February", "August", "May"] m = max(months) print(f"m = {m}") sys.exit(0)
m = May
Give each month a score.
In the following program, the score of
"February"
is 8 and the score of
"August"
is 7.
Then find the month with the biggest score.
""" Find the max (in order of increasing length) of a list of strings. """ import sys months = ["February", "August", "May"] m = max(months, key = len) print(f"m = {m}") sys.exit(0)
m = February
In the following program,
the score of
"February"
is now 1 and the score of
"August"
is 7.
""" Find the max (in chronological order) of a list of strings. """ import sys chronologicalOrder = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] months = ["February", "August", "May"] try: m = max(months, key = lambda month: chronologicalOrder.index(month)) except ValueError: print(f"Sorry, your list contains a string that is not a month.", file = sys.stderr) sys.exit(1) print(f"m = {m}") sys.exit(0)
m = August