+ 1

max()

Does max() only work with numbers? I tried using it on a list of words but it didn't return the longest word

12th Aug 2022, 5:38 PM
Gabby
3 ответов
+ 8
Gabby , you can use max() also for getting the longest wordf from a list. max() has a key-option, in the required case it has to be set to 'len', but it can also take other functions. print(max(["aaa", "x", "kkkkk", "zz"], key= len) returns "kkkkk"
12th Aug 2022, 5:50 PM
Lothar
Lothar - avatar
+ 3
# Hi, Gabby ! # No, the builtin function max works also with for example strings too. # The items are either arguments in max, or put inside an iterator: max("b", "d", "g", "f") # returns ”g”. max(["b", "d", "g", "f"]) # returns "g" max("bdgf") # returns ”g” max("bdgf", "bdz", "ajs") # returns "bdz" # If you want find to the longest word, you can set key=len, like: max("bdgf", "bdz", "ajs", key=len) # returns "bdgf" # https://code.sololearn.com/c64r4TnSUYbJ/?ref=app
12th Aug 2022, 5:51 PM
Per Bratthammar
Per Bratthammar - avatar
+ 3
Thanks 👍🏾
12th Aug 2022, 5:53 PM
Gabby