Using min() and max() With Strings
max() With Strings and Iterables of Strings. Using
max() with numeric values is arguably the most common and useful use case of these functions. However, you can also use the functions with strings and iterables of strings.
Behind the scenes, they use the character’s numeric value to find the minimum and maximum characters in the input string. For example, in the Unicode character table, the uppercase
A has a smaller numeric value than the lowercase
a. Python’s built-in
ord() function takes a single Unicode character and returns an integer representing the Unicode code point of that character.
In these examples, the code point for the uppercase
"A" is lower than the code point for the lowercase
"a". This way, when you call
max() with both letters, you get results that match the order of the underlying Unicode code points of the letters.
Finally, you can also call
max() with iterables of strings or with multiple string arguments. Again, both functions will determine their return value by comparing the strings alphabetically.
To find the smallest or largest string in an iterable of strings,
max() compare all the strings alphabetically based on the code points of the initial characters. In the first example, the uppercase
"H" comes before
"w" in the Unicode table.
min() immediately concludes that
"Hello" is the smallest string. In the second example, the lowercase
"w" comes after all the other strings’ initial letters. But note, there are two words that start with
"world". So, Python proceeds to look at the second letter of each word, and the result is that
"o" comes after
Become a Member to join the conversation.