The Python Oracle

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

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Drifting Through My Dreams

--

Chapters
00:00 Question
00:38 Accepted answer (Score 736)
00:53 Answer 2 (Score 14)
01:10 Answer 3 (Score 8)
01:34 Answer 4 (Score 5)
02:19 Thank you

--

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

Accepted answer links:
[Python documentation]: http://docs.python.org/whatsnew/2.5.html...
[max]: http://docs.python.org/library/functions...

Answer 4 links:
http://effbot.org/zone/python-list.htm

--

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.