+ 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. 😕😕😕
2 Respostas
+ 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'.
+ 1
Oh, ok. Thanks! 😁
EDIT: for those sorting by length and having issues, try:
sorted(iterable, key=len)