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

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


From the Python documentation itself, you can use max:

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


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:...


def longestWord(some_list):     count = 0    #You set the count to 0    for i in some_list: # Go through the whole list        if len(i) > count: #Checking for the longest word(string)            count = len(i)            word = i    return ("the longest string is " + word)

or much easier:

max(some_list , key = len)


matomo