Python has many pre-defined
functions, including the
max()
and min()
functions . Here's what they are-
The max() Function
This function is quite easy to understand. Like the name suggests, it takes a given sequence (list, tuple, dictionary, set, etc) and, in case of a number, gives the highest value as the output and in case of strings, gives the element that is alphabetically last in the sequence.
Let's look at an example to understand it better-
seq=("Hello", "Bye", "Donald", "Duck")
print(max(seq1))
The output-
Hello
Note: Uppercase characters are considered to be before lowercase ones.
So, if you have 2 elements in a sequence, 1 beginning with an uppercase
character and the other with a lowercase one, the max()
function
will give the element beginning with a lowercase character as the output
Here's an example of such a situation-
seq=("Zinc", "aluminum")
print(max(seq))
The output-
aluminum
If you include mixed data types in the sequence (like string and integer), you will get an error as this function can only be used with similar data types.
For example-
seq=("Hello", 123)
print(max(seq))
The output-
Traceback (most recent call last):
File "/Users/'username'/'folder'/'filename'", line 3, in <module>
print(max(seq))
^^^^^^^^
TypeError: '>' not supported between instances of 'int' and 'str'
To end this topic, here's an example of the function being executed on a sequence having numbers-
seq=(450, 30, 96, 120.3, 756)
print(max(seq))
The output-
756
The min() Function
The min()
function is the exact opposite of the
max()
function. It takes a given sequence, and gives the smallest
element as output. In case of strings, it takes the word beginning with the
earliest letter as per the alphabet as the smallest value.
An example with string values-
seq=("Hello", "Bye", "Donald", "Duck")
print(min(seq))
The output-
Bye
An example with numbers-
seq=(1, 784, 943, 102)
print(min(seq))
The output-
1
max()
function, you get an error if you mix string
data types with numerical data types like float and int.
That is all for this post on max() and min() functions. Follow for more interesting content on Python.
Happy coding,
Aarav Iyer