0

I am trying to get my head around single line evaluations and this is what I came up with. I am sure there is a better more pythonic what to write this line.

s1 = 'abcdef'
s2 = 'abcdefghi'

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

print(ln)  # prints 6

edit: updated code This is more understandable for me though the result is the same.

ln = len(s1) if len(s1) < len(s2) else len(s2)

This is much easier to read.

ln = min( len(s1), len(s2) )
Cœur
  • 37,241
  • 25
  • 195
  • 267
Eman
  • 83
  • 6
  • This is perfectly Pythonic. The most improvement is simply to replace `ln` with the evaluation you have. – Akshat Mahajan Jul 14 '16 at 21:01
  • 2
    That's fine to be honest, trying to find the shortest way to do something isn't always the best thing to do; making sure it's readable and understandable is more important – Peter Wang Jul 14 '16 at 21:01
  • 1
    `ln= min(len(s1), len(s2))`? – Aran-Fey Jul 14 '16 at 21:07
  • I changed the order of the inner s1 and s2 which makes it more readable `ln = len(s1) if len(s1) < len(s2) else len(s2)`. But I am going to go with @Rawing code. – Eman Jul 14 '16 at 23:47

1 Answers1

0

Just store the results of len in variables:

s1 = 'abcdef'
s2 = 'abcdefghi'
l1 = len(s1)
l2 = len(s2)

ln = l1 if l2 > l1 else l2

If you need to do this for more strings, you can use min. Doing this for just 2 strings is overkill though, and I don't recommend it:

ln = min(len(s) for s in (s1, s2, s3, ...))
Bahrom
  • 4,752
  • 32
  • 41
  • You should store those values, because if you don't, python will evaluate this length each time it is asked for it. For long strings or more complicated functions, computations might be costly and slow down the program – fulaphex Jul 14 '16 at 21:07
  • @Fulaphex why write more code right now, just to hedge against an imaginary future where hypothetical costly computations, if put in a loop that doesn't yet exist, might slow it down enough to be a problem? Cross that bridge when you get to it. – TessellatingHeckler Jul 14 '16 at 21:14
  • It was a suggestion for future needs and a word of comment, on why in the answer this solution was used, what benefits are in such a way. – fulaphex Jul 14 '16 at 21:16
  • 2
    Writing `ln = min(map(len, (s1, s2)))` does not seem too difficult to read. – Noctis Skytower Jul 14 '16 at 21:34
  • 2
    @Fulaphex, Python doesn't calculate the length each time you request it. [Build-in Iterables handle it in an appropiate way.](http://stackoverflow.com/questions/1115313/cost-of-len-function) – Hamlett Jul 14 '16 at 21:38