Finding maximum (max) text-item in a list using python -
why max function operates differently in 2 list below:
>>> list1=['the school','boy', 'the wise old man'] >>> max(list1) 'the wise old man' list2=['made', 'with', 'then', 'happy home', 'came', 'this', 'them', 'from', 'have', 'into'] >>> max(list2) 'with'
obviously in list2, 'happy home'
is supposed 'max'
has more number of text others in list.
any ideas why? thanks.
max()
compares strings lexicographically; found element sorted last. thus, 'the wise old man'
comes after the school
, alphabetically speaking.
to longest string instead, pass function key
argument of max()
:
max(list2, key=len)
generally speaking, without key
function, max()
find value value > othervalue
true other values in input sequence.
the key
argument, if provided, gives max()
different value compare decide item in sequence largest.
Comments
Post a Comment