0

Can someone please explain to me how is max() function working in the following code?

strings = ['enyky', 'benyky', 'yely','varennyky']
print(max(strings))

max() function should return the longest string in following list, that is 'varennyky', instead I am getting 'yely' as output. Can someone please explain me?

1 Answers1

-1

It's returning the last item in sort order.

You can use the key= parameter for max() (like you'd use for sorted(), see below) to use len(x) for the key instead.

>>> strings = ['enyky', 'benyky', 'yely','varennyky']
>>> sorted(strings)
['benyky', 'enyky', 'varennyky', 'yely']
>>> sorted(strings, key=len)
['yely', 'enyky', 'benyky', 'varennyky']
>>> max(strings, key=len)
'varennyky'
>>>
AKX
  • 152,115
  • 15
  • 115
  • 172