The Python Oracle

Python's most efficient way to choose longest string in list?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2 Looping

--

Chapters
00:00 Python'S Most Efficient Way To Choose Longest String In List?
00:31 Accepted Answer Score 764
00:43 Answer 2 Score 3
00:58 Answer 3 Score 3
01:30 Answer 4 Score 8
01:46 Thank you

--

Full question
https://stackoverflow.com/questions/8733...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list #listcomprehension

#avk47



ACCEPTED ANSWER

Score 764


From the Python documentation itself, you can use max:

>>> mylist = ['123','123456','1234']
>>> print max(mylist, key=len)
123456



ANSWER 2

Score 8


What should happen if there are more than 1 longest string (think '12', and '01')?

Try that to get the longest element

max_length,longest_element = max([(len(x),x) for x in ('a','b','aa')])

And then regular foreach

for st in mylist:
    if len(st)==max_length:...



ANSWER 3

Score 3


len(each) == max(len(x) for x in myList) or just each == max(myList, key=len)




ANSWER 4

Score 3


To get the smallest or largest item in a list, use the built-in min and max functions:

 lo = min(L)
 hi = max(L)  

As with sort, you can pass in a "key" argument that is used to map the list items before they are compared:

 lo = min(L, key=int)
 hi = max(L, key=int)

http://effbot.org/zone/python-list.htm

Looks like you could use the max function if you map it correctly for strings and use that as the comparison. I would recommend just finding the max once though of course, not for each element in the list.