+ 1

[✅SOLVED✅] How does max() act on a list of strings?

What exactly does max() do in Python with a list of strings? As I currently understand, it finds the longest word in the list. Code: ls = ["hi", "world", "i", "am", "alive"] print(max(ls)) Output: world However, that does not explain the fact that the output is never "alive," but always "world." I've tried in the code playground, PyCharm, repl.it (really good online compiler for many languages), and the Python shell. 😕😕😕

6th Oct 2017, 3:20 PM
LunarCoffee
LunarCoffee - avatar
2 Respuestas
+ 9
Actually, max() will compare the strings alphateb-wise or to be more precise - ASCII-table-order-wise. This is why max('abracadabra', 'zonk') will be 'zonk', not 'abracadabra'.
6th Oct 2017, 5:29 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 1
Oh, ok. Thanks! 😁 EDIT: for those sorting by length and having issues, try: sorted(iterable, key=len)
6th Oct 2017, 5:33 PM
LunarCoffee
LunarCoffee - avatar