Strings are compared by lexicographical ordering, not by length. S
comes after D
in the alphabet:
>>> 'Superman' > 'Dudley Do-Right'
True
An inefficient way to replicate what max()
does, would be to sort the input sequence and pick the last value for the result. So [20, 10, 8, 15]
, when sorted, puts 20
last and that's what max()
returns. Sorting the strings in Heroes
results in Superman
being listed last.
If you wanted to find the longest string, use the key
argument to max()
:
max(Heroes, key=len)
Here, instead of comparing values in Heroes
directly, max()
compares the values by the return value of the key
argument; now the value for which len()
returns the largest value is returned as the maximum.
Demo:
>>> Heroes = ['Superman', 'Batman', 'Dudley Do-Right', 'Luke Skywalker']
>>> max(Heroes, key=len)
'Dudley Do-Right'