13

Something like max(len(s1), len(s2)) will only return the maximum length. But if I actually want to find out which string is longer, and perhaps save it to another string, how is that done? max(s1,s2) seems to return the string with the larger value, but not necessarily the longest.

Note: this has to be done without lists or arrays.

3 Answers 3

39

max takes a key function which causes max to take the max key(val) for each val, yet still return the val, to wit:

>>> max("foobar", "angstalot")
'foobar'
>>> max("foobar", "angstalot", key=len)
'angstalot'
Sign up to request clarification or add additional context in comments.

1 Comment

>>> max("foobar", "foobak", key=len) >>> 'foobar' max might not be best solution here?
1
def longest(a, b):
   if len(a) > len(b):
       return a
   return b

9 Comments

It works, but it's not idiomatic because precisely that functionality, in a more general and useful form, already exists among the builtins.
Maybe you should edit the question to say "what is the one true way to do this?".
It's neither my downvote nor my question. But apart from that, a downvote does not mean "the answer doesn't address the letter of the question" but "the answer is not useful". And it arguably isn't, because it teaches unassuming readers to re-implement basic functionality instead of using the built in functions.
Fair enough. I agree that using the built-in is more 'pythonic' but disagree that a non-one-liner is not useful where a one-liner is available.
It's not about one liners (more often than not that leads to less readable code), but about re-implementing using four lines for something which is can be stated clearer, better and more general in less code.
|
1

Just a simple conditional expression based on the length of each string is all that is needed:

longest = s1 if len(s1) > len(s2) else s2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.