Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given two strings, how do I assign the shorter string to one variable and the longer string to another

I am learning python and would like to know if there is a pythonic way of doing this. Of course I can do an

if len(a) > len(b) :
  (x,y) = (b,a)

and so on. But this seems a bit verbose. Is there a more beautiful way to do this in python?

like image 203
Can't Tell Avatar asked Dec 10 '22 05:12

Can't Tell


1 Answers

Sorting seems a bit overkill. You can do it in one line just with if.

x,y = (a,b) if len(a) < len(b) else (b,a)
like image 168
khelwood Avatar answered Dec 12 '22 17:12

khelwood