In today’s post, we’ll talk about the max()
function in Python.
We’ll also work on a practice question that accepts a list and returns a new list with certain maximum values removed.
Here are some topics we’ll cover in our post:
- What does the
max()
function do? - Using the
max()
function with multiple arguments - Using
max()
with iterables - Preventing
ValueError
exceptions - Customizing the sort criteria used by the
max()
function - Using lambda functions in Python
Table of Contents
Key Concepts
The Python max()
function is a built-in function that returns the largest value among its input.
To use this function, we can pass multiple arguments to it, or pass a single iterable.
Using the max() function with multiple arguments
Using the max()
function with multiple arguments is straightforward.
If the arguments are numbers, the max()
function returns the largest number.
If the arguments are strings, the function returns the ‘largest’ string based on alphabetical order.
If the arguments are of different types, such as numbers and strings, the function throws a TypeError
exception.
Let’s look at some examples:
a = max(1, 19, -4, 6, -2)
b = max(1.4, -2, -5.1, 21.5, 0, 4.7, 9, 17)
c = max('Abigail', 'Joshua', 'Naomi', 'Nancy')
d = max('P', 'Q', 'p', 'q')
print(a)
print(b)
print(c)
print(d)
e = max(3, 123, 'A')
print(e)
If you run the code above, you’ll get the following output:
19
21.5
Naomi
q
Traceback (most recent call last):
File "...", line 31, in <module>
e = max(3, 123, 'A')
TypeError: '>' not supported between instances of 'str' and 'int'
The first two examples (a
and b
) are self-explanatory.
For the third example, when we arrange 'Abigail'
, 'Joshua'
, 'Naomi'
and 'Nancy'
alphabetically in descending order, 'Naomi'
is ranked last (since ‘N’ comes after ‘A’ and ‘J’ and ‘o’ in Naomi comes after ‘n’ in Nancy). Hence, we get ‘Naomi’ as the output.
The fourth example (d
) indicates that when you compare uppercase letters with lowercase, lowercase is considered greater. Hence, we get q
as the output.
The last example (e
) shows that when we pass numbers and strings to the max()
function, we get an error.
Using max() with iterables
Next, let’s look at how we can use the max()
function with iterables.
Iterables refer to anything that can be looped over, such as a list, tuple, string or dictionary.
If we pass an empty iterable to the max()
function, we’ll get an error.
Let’s look at some examples:
a = "Hello World"
b = [2, 17, 9, 18, -3, 4.1, 5]
c = {5:12, 6:99, 7:16, 8:20}
d = []
print(max(a))
print(max(b))
print(max(c))
print(max(d))
In the code above, we first declare and initialize four iterables – a string a
, a list b
, a dictionary c
and an empty list d
.
Next, we pass the iterables to the max()
function and use the print()
function to print the outputs.
If you run the code above, you’ll get the following results:
r
18
8
Traceback (most recent call last):
File "...", line .., in <module>
print(max(d))
ValueError: max() arg is an empty sequence
The first two examples should be quite easy to understand.
The third example shows what happens when we pass a dictionary to the max()
function; it returns the largest key in the dictionary (not the largest value). Hence, we get 8 as the output.
The last example shows what happens when we pass an empty iterable to the function. As d
is an empty list, the max()
function is unable to get the largest item in the list. Hence, it throws a ValueError
exception.
If we want to prevent such errors, we can pass an additional argument – default
– to the function. This argument specifies the value to return if the iterable is empty. Let’s look at an example:
a = []
print(max(a, default = '-1'))
print(max(a))
If you run the code above, you’ll get the following output:
-1
Traceback (most recent call last):
File "...", line .., in <module>
print(max(a))
ValueError: max() arg is an empty sequence
When we pass an empty list and the default = '-1'
argument to the max()
function (on line 2), we get -1 as the output.
In contrast, when we do not pass the default
argument (on line 3), we get an error.
Customising the sort criteria
By default, the max()
function returns the largest item based on the value of the items. If you want to define the largest item using a different criteria, you can pass an additional argument – key
– to the function.
key
can be assigned a named function or a lambda function.
Using named functions
We’ll discuss what a lambda function is later. For now, let’s look at how we can use the key
argument with a named function.
Suppose we want max()
to return the longest string in a list of strings.
To do that, we can use the len()
function, by assigning the name of the function (len
) to the key
argument, as shown in the example below:
a = ['Python', 'C#', 'Java', 'Ruby']
print(max(a))
print(max(a, key=len))
If you run the code above, you’ll get the following output:
Ruby
Python
When we sort the strings 'Python'
, 'C#'
, 'Java'
and 'Ruby'
alphabetically, 'Ruby'
is considered the ‘largest’ string as ‘R’ comes after ‘C’, ‘J’ and ‘P’.
Hence, max(a)
gives us 'Ruby'
as the output.
However, when we pass the argument key=len
to the max()
function, we get 'Python'
as the output instead. This is because the argument key=len
tells the max()
function to return the largest item in a
based on the len()
function.
Since len('Python')
is the greatest, we get 'Python'
as the output.
If two items have the same length, the max()
function returns the first item. For instance,
b = ['C#', 'Java', 'Ruby']
print(max(b, key=len))
gives us
Java
as the output.
Using lambda functions
Next, let’s look at how we can use lambda functions with the key
argument.
In Python, a lambda function refers to an anonymous (i.e. unnamed) function that only has one expression. This expression is evaluated and the result (if any) is returned.
The syntax of a lambda function is as follows:
lambda arguments : expression
While normal functions are defined using the def
keyword, lambda functions are defined with the lambda
keyword.
After the lambda
keyword, we list the arguments of the function, followed by a colon. After the colon, we specify the expression we want the function to evaluate.
For instance,
lambda x, y : x + y
is a lambda function with two arguments – x
and y
. It evaluates the expression x + y
(on the right side of the colon) and returns the result.
To call a lambda function, we need to surround the function with a pair of parentheses.
In addition, we need to pass the arguments to the function using a pair of parentheses, similar to how we call a normal function.
To call the function above, we write:
a = (lambda x, y : x + y) (2, 3)
print(a)
(2, 3)
represents the arguments passed to the function. If we run the code above, we’ll get
5
as the output.
Let’s look at two more examples:
(lambda x, y, z : print(x, y, z))('Hello', 'Python', 'World')
l = (lambda x : len(x))('Ragdoll')
print(l)
The first lambda function above accepts three arguments (x
, y
and z
) and prints their values using the expression print(x, y, z)
. We pass the strings 'Hello'
, 'Python'
and 'World'
as arguments to the function.
The second lambda function accepts one argument (x
) and returns the length of x
(i.e. it returns len(x)
). We pass the string 'Ragdoll'
to the function.
If you run the code above, you’ll get the following output:
Hello Python World
7
Now that we are familiar with lambda functions, let’s look at an example of how we can use it with the max()
function.
Suppose we want the max()
function to return the largest item in a dictionary based on the value (instead of the key) of the items in the dictionary, we can use the following code:
c = {5:12, 6:99, 7:16, 8:20}
print(max(c, key=lambda x : c[x]))
Here, we assign the lambda function lambda x : c[x]
to the key
argument. This function returns c[x]
when given the argument x
. In other words, it returns the value of each item in the dictionary c
, when given its key x
.
As a result, the max()
function now uses the value of the dictionary (instead of the key) to define the largest item.
If you run the code above, you’ll get the following output:
6
This is because 6 is associated with the largest value 99. Although the max()
function defines the largest item based on the value of the items, it will still return the key of the largest item. Hence, we get 6 (instead of 99) as the output.
Practice Question
Now, let’s move on to the practice question for today.
Today’s practice question requires us to write a function called removeAbsoluteMax()
that accepts a list of numbers. This function returns a new list with the same items as the input list, except for those items whose absolute value (i.e. value of a number without its sign) is the largest. These values are not included in the new list returned.
Expected Results
To test your function, you can use the following statements:
a = [12, 3, 2, 11, 17]
b = [1, -5, 2, 4]
c = [2, -6, 4, 5, -1, 6, 2, -3]
print(removeAbsoluteMax(a))
print(removeAbsoluteMax(b))
print(removeAbsoluteMax(c))
You should get the following output:
[12, 3, 2, 11]
[1, 2, 4]
[2, 4, 5, -1, 2, -3]
in the first example above, the removeAbsoluteMax()
function returned a new list without the number 17.
In the second example, the function returned a list without the number -5. Although -5 is not the largest item in the input list, its absolute value (5) is the largest. Hence, -5 is not included in the list returned.
In the last example, the numbers -6 and 6 are not included in the list returned as both their absolute values (6) are the largest.
Additional Notes
You can refer to this post for more details on working with absolute values.
Suggested Solution
The suggested solution for today’s practice question is:
def removeAbsoluteMax(a):
maxToRemove = max(a, key=abs)
b = []
for i in range(len(a)):
if abs(a[i]) != abs(maxToRemove):
b.append(a[i])
return b
Here, we first define a function called removeAbsoluteMax()
that has one parameter a
.
Next, we use the max()
function to get the value of the item(s) in a
with the largest absolute value. We do that by passing key=abs
to the function, where abs
is the name of the built-in abs()
function.
For instance, if a = [-1, 2, 5, -6]
, the max()
function returns -6 as the result, which we assign to a variable called maxToRemove
.
Next, we declare an empty list called b
.
We then use a for
loop to iterate through a
and append the items in a
to b
only if the absolute value of that item is different from the absolute value of maxToRemove
.
For instance, if maxToRemove
is -6, and the item in a
is 6, the if
condition on line 7 evaluates to False
and we do not append 6 to b
.
On the other hand, if the item in a
is 3, the if
condition evaluates to True
and we append 3 to b
.
After looping through all the items in a
and appending the appropriate items to b
, we return b
on line 10.
With that, the function is complete.