How to Use Key Function in Max() and Min() in Python

Learn to use key parameters in max( ) and min( ).

Photo by MinuteKEY on Unsplash

Key Function in Max() and Min() in Python

A key function is a callable that returns a value used for sorting or ordering.

The below mentioned functions accept key functions to control how elements are ordered or grouped.

  1. min()
  2. max()
  3. list.sort()
  4. sorted()
  5. heapq.merge()
  6. heapq.nsmallest()
  7. heapq.nlargest()
  8. itertools.groupby()

Let’s see how to use key function in min() and max() in this story.

Refer to my story for how to use the key function in the sorted() function.


max()

  1. Return the largest item in an iterable or the largest of two or more arguments.
  2. If one item is given, it should be iterable. The largest item in the iterable is returned. 
    max(iterable, *[, key, default])
  3. If two or more positional arguments are provided, the largest of the positional arguments is returned.
    max(arg1, arg2, *args[, key])
  4. There are two optional keyword-only arguments.
  • key– key function where the iterables are passed and comparison is performed based on its return value
  • The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and the default is not provided, a ValueErroris raised.

5. If multiple items are maximal, the function returns the first one encountered.


min()

  1. Return the smallest item in an iterable or the smallest of two or more arguments.
  2. If one positional argument is provided, it should be iterable. The smallest item in the iterable is returned.
    min(iterable, *[, key, default])
  3. If two or more positional arguments are provided, the smallest of the positional arguments is returned.
    min(arg1, arg2, *args[, key])
  4. There are two optional keyword-only arguments.
  • The key argument specifies a one-argument ordering function. The key function where the iterables are passed and comparison is performed based on its return value
  • The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and the default is not provided, a ValueError is raised.

5. If multiple items are minimal, the function returns the first one encountered.


Examples Covered:

Image Source: Author

Example 1: Find the largest and smallest number in an iterable.

l1=[12,4,2,6,8,35]
#list
print (max(l1))#Output:35
print (min(l1))#Output:2
t1=(12,3,2,56,45)
#tuple
print (max(t1))#Output:56
print (min(l1))#Output:2

Example 2: Finding the largest and smallest value in the dictionary.

By default, max() and min() will return the largest and smallest key in the dictionary.

d1={'a':12,'b':5,'c':7}
#by default it will return the largest and smallest key in the dictionary
print (max(d1))#Output:c
print (min(d1))#Output:a

#finding largest and smallest value in the dictionary
print(max(d1.values()))#Output:12
print (min(d1.values()))#Output:5

Example 3:Finding the largest and smallest strings in the iterable.

max() and min() will return the result based on the ASCII value of each character.

Image Source: Author

max() will print the character which has the largest ASCII value
min() will print the character which has the smallest ASCII value.

l1=['red','BLUE','yellow',"Green"]
print (max(l1))#Output:yellow
print (min(l1))#Output:BLUE

l2='Apple'
print (max(l2))#Output:p
print (min(l2))#Output:A

4. Finding the largest and smallest item among the arguments

print (max('apple','APPLE','banana'))#Output:banana
print (min('apple','APPLE','banana'))#Output:APPLE
print (max(14,1,5))#Output:14
print (min(14,1,5))#Output:1

5. Finding the largest and smallest item in the iterable containing mixed datatypes.

print (max('apple','APPLE','banana',1,2))
#Output:TypeError: '>' not supported between instances of 'int' and 'str'
print (min('apple','APPLE','banana',1,2))
#Output:TypeError: '<' not supported between instances of 'int' and 'str'

l1=['a',1,2]
print(max(l1))
#Output:TypeError: '>' not supported between instances of 'int' and 'str'
print(min(l1))
#Output:TypeError: '<' not supported between instances of 'int' and 'str'

Key function

We can also compare the iterable based on the function specified in the key parameter. It can be

  • Built-in function
  • User-defined function
  • Lambda function
  • itemgetter
  • attrgetter

1. Built-in function

  • len()-It will count the length of the object. If we specify len as a key function in min(), max(), it will return the smallest and largest item based on the length.

Example 1: Finding the largest and smallest key and value in the dictionary using key function -len()

#Finding largest and smallest key in the dictionary using len()
l1={'carrot':'vegetable','red':'color','apple':'fruit'}
#min() and max() based on len function
print (min(l1,key=len))
#Output:red
print (max(l1,key=len))
#Output:carrot

#Finding largest and smallest values in the dictionary based on len()
print (min(l1.values(),key=len))
#Output:color
print (max(l1.values(),key=len))
#Output:vegetable

Example 2: Finding the largest and smallest item in the list using len()

#Finding largest and smallest item by using len()
l1=['blue','green','red','orange']
print (min(l1,key=len))
#Output:red
print (max(l1,key=len))
#Output:orange
  • abs()– It will return the absolute value of a number. If we specify abs as key function in min(), max(), it will return the smallest and largest item based on the absolute value

Example 3: Finding the largest and smallest item on the list based on the absolute value


l1=[1,-4,5,-7,-9,2]
print (min(l1,key=abs))
#Output:1
print (max(l1,key=abs))
#Output:-9
  • str.lower()-str.lower() will convert all uppercase characters to lower case. If we mention key function as str.lower in min() and max(), it will perform lower on all items present in the iterable, and then find the smallest and largest item in iterable.

Example 4: Finding the largest and smallest string among the arguments based on key function(str.lower)

print (max('a','A','B','c','Z',key=str.lower))
#Output:Z
print (min('a','A','B','c','Z',key=str.lower))
#Output:a

#without key function
print (max('a','A','B','c','Z'))
#Output:c
print (min('a','A','B','c','Z'))
#Output:A

2. User-defined function

We can specify key functions as user-defined functions also.

Example 1: By default, min(), max() function will compare a list of tuples based on the first element. Here we mentioned a user-defined function to take the second element. So, now it returns the largest/smallest number from the list of tuples based on the second element.

# define function to take second element
def cmp_key(e):
return e[1]

l1 = [(1, 2, 3), (2, 1, 3), (11, 4, 2), (9, 1, 3)]

# Based on user defined function
print(min(l1, key=cmp_key))
# Output:(2,1,3)
print(max(l1, key=cmp_key))
#Output:(11,4,2)

3.Lambda function

We can mention the key function as a lambda function also. Based on that lambda function, min() and max() will sort the iterable.

Example 1: Using key function as a lambda function in max() and min()

By default, min(), and max() will compare string based on lexicographic order.

lexicographic order is a generalization of the way words are alphabetically ordered based on the alphabetical order of their component letters.

If we mention a key function as

key=lambda x:x.lower()

It will convert all strings to lower case and then compare the results and return the largest/smallest item.

l1=['red','RED','Yellow','blue','pink']
#Without key function,it will compare based on lexicographic order
print (max(l1))#Output:red
print (min(l1))#Output:RED

print (max(l1,key=lambda x:x.lower()))#Output:Yellow
print (min(l1,key=lambda x:x.lower()))#Output:Blue

Example 2: Sorting list of tuples based on the second element in the tuple. Lambda function which returns the second element is mentioned as a key function.

l1=[(1,2,3),(3,1,1),(8,5,3),(3,4,2)]

#Finding the largest/smallest item based on second element in the tuple.
# lambda function returns second element in the tuple
print (min(l1,key=lambda x:x[1]))
#Output:(3, 1, 1)
print (max(l1,key=lambda x:x[1]))
#Output:(8, 5, 3)

#Without key function
#by default it will take the first element in the tuple.
print (min(l1))#Output:(1, 2, 3)
print (max(l1))#Output:(8, 5, 3)

4.itemgetter

The operator is a built-in module that contains many operators.

itemgetter(n) constructs a function that assumes an iterable object (e.g. list, tuple, set) as input, and fetches the n-th element out of it.

As per Python Documentation:

operator.itemgetter(item)
operator.itemgetter(*items)

Return a callable object that fetches item from its operand using the operand’s __getitem__() method. If multiple items are specified, returns a tuple of lookup values. For example:

After f = itemgetter(2), the call f(r) returns r[2].

After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3]).

Example:1 Finding the largest/smallest element in the list of tuples based on the second element in the tuple.

itemgetter() will return the function that fetches the second element in the tuple.

By default, if we didn’t specify the key function, it will sort based on the first element in the tuple.

from operator import itemgetter
l1=[(1,2,3),(3,1,1),(8,5,3),(3,4,2)]

#Finding the largest/smallest element in the list of tuples based on second element in the tuple.
print (max(l1,key=itemgetter(1)))
#Output:(8,5,3)
print (min(l1,key=itemgetter(1)))
#Output:(3,1,1)

Example 2:Finding the largest/smallest item in the list of dictionaries based on the key(age) in the dictionary.

from operator import itemgetter
#Creating list of dictionaries
d1=[{'name':'indhu','age':30},
{'name':'karthi','age':7},
{'name':'sarvesh','age':3}]

#Finding largest/smallest item  based on key(age) in the dictionary
print (min(d1,key=itemgetter('age')))
#Output:{'name': 'sarvesh', 'age': 3}
print (max(d1,key=itemgetter('age')))
#Output:{'name': 'indhu', 'age': 30}

Example:3 Finding the largest/smallest item in the list of dictionaries based on dictionary values

from operator import itemgetter
d={'a':[1,2,3],'b':[3,4,5],'c':[1,1,2]}
print (min(d.values(),key=itemgetter(1)))
#Output:[1, 1, 2]
print (max(d.values(),key=itemgetter(1)))
#Output:[3, 4, 5]

5.attrgetter

operator.attrgetter (attr)
operator. attrgetter (*attrs)

Return a callable object that fetches attr from its operand. If more than one attribute is requested, returns a tuple of attributes. The attribute names can also contain dots.

Example: Finding the largest/smallest item from the list of class objects by using attrgetter.

from operator import attrgetter

class Student:
def __init__(self, name, rollno, grade):
        self.name = name
        self.rollno = rollno
        self.grade = grade

def __repr__(self):
return f"{self.name}-{self.rollno}-{self.grade}"


# Initializing Student Objects
s1 = Student("karthi", 15, "second")
s2 = Student("Indhu", 12, "fifth")
s3 = Student("Sarvesh", 21, "first")

# Creating list of student objects
s4 = [s1, s2, s3]

# Finding largest/smallest item from list of objects based on attribute:rollno
print (max(s4, key=attrgetter('rollno')))#Output:Sarvesh-21-first
print (min(s4, key=attrgetter('rollno')))#Output:Indhu-12-fifth

default parameter

We can also define a default value to return if the iterable is empty. If the default parameter is not mentioned, it will raise ValueError.

Example 1: The default parameter is not mentioned and the iterable is empty.

l1=[]
print (max(l1))
#Output:ValueError: max() arg is an empty sequence
print (min(l1))
#Output:ValueError: min() arg is an empty sequence

Example 2:Default value is mentioned.

l1=[]
print (max(l1,default=None))
#Output:None
print (min(l1,default=None))
#Output:None

Conclusion:

  • min(),max() -Raises TypeError, if iterable contains mixed data types.
  • min(),max()-Raises ValueError,if iterable is empty.

Resources(Python documentation):

key-function

min()

max()

operator.attrgetter

operator.itemgetter

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s