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.

quantum
  • 3,672
  • 29
  • 51
user1689935
  • 319
  • 2
  • 4
  • 6

3 Answers3

40

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'
Claudiu
  • 224,032
  • 165
  • 485
  • 680
1
def longest(a, b):
   if len(a) > len(b):
       return a
   return b
Joe
  • 46,419
  • 33
  • 155
  • 245
  • 1
    It works, but it's not idiomatic because precisely that functionality, in a more general and useful form, already exists among the builtins. –  Sep 21 '12 at 22:00
  • 2
    Maybe you should edit the question to say "what is the one true way to do this?". – Joe Sep 21 '12 at 22:02
  • 1
    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. –  Sep 21 '12 at 22:04
  • 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. – Joe Sep 21 '12 at 22:15
  • 2
    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. –  Sep 21 '12 at 22:18
  • No I completely get your point. And I agree. Just a bit grumpy about the downvote after a heavy week, I think. Time to close SO. – Joe Sep 21 '12 at 22:21
  • +1 to offset the downvote ... because strictly speaking this answers OP's question... Its fairly obvious from the +12 the other answer is the more pythonic answerr... – Joran Beasley Sep 21 '12 at 22:32
  • If TOOWTDI weren't hard to remember and ridiculous to pronounce, nobody would have these arguments. :) – abarnert Sep 21 '12 at 23:04
  • @abarnert: I suspect Don't Re-invent The Wheel is closer to delnan's intent. – JS. Sep 22 '12 at 00:10
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
martineau
  • 119,623
  • 25
  • 170
  • 301