views:

1152

answers:

4

I have a list of variable length and am trying to find (most likely) a list comprehension to allow me to see if the list item currently being evaluated is the longest string contained in the list. And am using Pythong 2.6.1

ie.

mylist = ['123','123456','1234']

for each in mylist:
    if condition1:
        do_something()
    elif ___________________: #else if each is the longest string contained in mylist:
        do_something_else()

I'm brand new to python and I'm sure I'm just having a brain fart. Surely there's a simple list comprehension that's short and elegant that I'm overlooking?

Thanks!

+22  A: 

From the Python documentation itself, you can use max:

>>> mylist = ['123','123456','1234']
>>> print max(mylist, key=len)
123456
Paolo Bergantino
Thank you very much.
Absolutely beautiful.
Kenneth Reitz
A: 

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

HarryM
A: 

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 (see below), you can pass in a key function

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.

ghills
A: 

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