Here's the code in question:
my_list = ['apples', 'oranges', 'cherries', 'banana']
print(max(my_list)
Why does it print 'oranges' instead of 'cherries'?
Here's the code in question:
my_list = ['apples', 'oranges', 'cherries', 'banana']
print(max(my_list)
Why does it print 'oranges' instead of 'cherries'?
Strings are sorted lexicographically, relative to each other. o
comes after a
, b
, and c
. The length isn't a factor unless the strings are identical up to that point, in which case the shorter string is judged as 'less'. max()
, then, produces the lexicographically greatest string (i.e. furthest back in the dictionary).
If you want to sort by length, you have to give the max()
function a key (for example, the len()
function):
>>> my_list = ['apples', 'oranges', 'cherries', 'banana']
>>> print(max(my_list))
oranges
>>> print(max(my_list, key=len))
cherries
The max()
function returns the item with the highest value, or the item with the highest value in an iterable.
If the values are strings, an alphabetically comparison is done.