1square = {2: 4, -3: 9, -1: 1, -2: 4}
2
3# the largest key
4key1 = max(square)
5print("The largest key:", key1) # 2
6
7# the key whose value is the largest
8key2 = max(square, key = lambda k: square[k])
9
10print("The key with the largest value:", key2) # -3
11
12# getting the largest value
13print("The largest value:", square[key2]) # 9
14
1# find largest item in the string
2print(max("abcDEF"))
3
4# find largest item in the list
5print(max([2, 1, 4, 3]))
6
7# find largest item in the tuple
8print(max(("one", "two", "three")))
9'two'
10
11# find largest item in the dict
12print(max({1: "one", 2: "two", 3: "three"}))
133
14
15# empty iterable causes ValueError
16# print(max([]))
17
18# supressing the error with default value
19print(max([], default=0))
20
1i = max(2, 4, 6, 3)
2
3print(i)
4# Result will be 6 because it is the highest number
1nums = [1,2,3,1,1,3,3,4,4,3,5] #list
2counts = collections.Counter(nums) # create a dict of counts
3#using counts.get() fun as custom function
4return max(counts.keys(), key=counts.get)
1The max() function returns the largest of the input values.
2
3Syntax:
4 max(iterable, *[, key, default])
5 max(arg1, arg2, *args[, key])
6
7 PARAMETER DESCRIPTION
8 iterable | An iterable object like string, list, tuple etc.
9 (required)
10 default | The default value to return if the iterable is empty.
11 (optional)
12 key | It refers to the single argument function to customize the sort
13 (optional) order. The function is applied to each item on the iterable.
14
15
16Example:
17 max([2, 1, 4, 3]) # Output: 4
18 max([], default=0) # supressing the error with default value, Output: 0
19 max("c", "b", "a", "Y", "Z") # Output: c
20 max("c", "b", "a", "Y", "Z", key=str.lower) # Output: Z
21