Python max() function

max() function overview

The max() function returns the largest element of an iterable or the largest argument passed to it. It can be used on numbers, strings and iterables. The opposite function of max() is the min() function, which returns the smallest element.

numbers and max()

If one or more number is passed to the max() function it will return the highest number. Numbers can be represented as float, integers or complex numbers. # max() function on numbers highest = max(1, 3, 5, 4, 2.2) print(highest) The max() function picks the highest number of the arguments passed and returns it. 5

strings and max()

If the max() function is used with strings, the highest item in the alphabetical order is returned. # max() function on strings result = max('aa', 'ab', 'ac') print(result) In this example the first letter is the same in every string, therefore the highest item of the second letter is returned. ac

lists and max()

The max() function returns the highest element in a list. # max() function on lists numbers = [5, 1, 3, 4, 2] largestNumber = max(numbers) print(largestNumber) The largest number of the list numbers is selected and returned. 5

max() and dictionaries

The max() function returns on default the largest key of a dictionary. The key parameter can be used to select the largest value. # max() on dictionaries myDict = {1: 6, 2: 8, 3: 7, 4: 9} maxKey = max(myDict) print(maxKey) The highest value key is selected, the values are not considered on default. 4

syntax of max()

The syntax of the max() function is for iterables: max(iterable, [iterables, key, default]) And for non-iterables: max(item1[, item2, item3, ... itemN])

arguments of max()

The arguments of the max() function are either an iterable or one or more items to compare.

return value of max()

The max() function returns the largest element from an iterable or the largest argument passed to it, if multiple arguments were passed to it.



Click to jump to section