I am relatively new to Python and i have been going over the documentation for various built-in functions.
When it comes to max/min functions:
`max(arg1, arg2, *args[, key])` or `max(iterable[, key])`
I know that arg1, arg2 etc or iterable could be a sequence of random values, however what is the role of the "key" element? Can someone give me an example of its application?
Normally when i see this built-in function, i automatically imagine a random list say x = [1,2,3] and going max(x) would yield the value of 3. However, what could the "key" feature offer me to manipulate this function some other way than just going through a simple straightforward list?
I am new to Python and not really up to speed with all the jargon in Python Docs.
Thanks, Ed
The Python max() function is used to find the largest value in a list of values. The Python min() function is used to find the lowest value in a list. The list of values can contain either strings or numbers. You may encounter a situation where you want to find the minimum or maximum value in a list or a string.
To find the maximum or minimum of a sequence, you must look at each element once, thus you can't get better than O(n). Of course, Python min and max have O(n) too: docs. You can write your own min/max function with a for loop and it will have the same complexity, but will be slower because it is not optimized in C.
The min() function returns the item with the lowest value, or the item with the lowest value in an iterable. If the values are strings, an alphabetically comparison is done.
The key is used to pass a custom comparison function.
Example: output max
by length of list, where arg1, arg2 are both lists.
>>> max([1,2,3,4], [3,4,5], key=len)
[1, 2, 3, 4]
Example: output max by sum of elements of args' lists
>>> max([1,2,3,4,5], [3,4,5], key=sum)
[1, 2, 3, 4, 5]
>>> max([1,2,3,4], [3,4,5], key=sum)
[3, 4, 5]
You can similarly use specific comparison functions for different arg objects.
You can use it when your you want to find the max of a sequence and you'd like a specific definition of max.
For example, say I have a list of tuple
. If I just use max
without the key
argument, it will by default use the first item in each tuple
>>> l = [(1,3), (2,4), (1,9), (4,1)]
>>> max(l)
(4, 1)
But what if I want the max from the list, but by considering the second element of the tuple
?
>>> max(l, key = lambda i : i[1])
(1, 9)
# Or
>>> import operator
>>> max(l, key = operator.itemgetter(1))
(1, 9)
Also what about a list of strings, and you want to find the max as if they were the numeric values?
>>> l = ['4', '11', '6', '31']
Just using max
will sort them lexicographically
>>> max(l)
'6'
But again I can use key
>>> max(l, key = lambda i: int(i))
'31'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With