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?

0

1 Answer 1

-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'
>>>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.