I have a list of variable length and am trying to find a way to test if the list item currently being evaluated is the longest string contained in the list. And I am using Python 2.6.1
For example:
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!
What should happen if there are more than 1 longest string (think '12', and '01')?
Try that to get the longest element
And then regular foreach
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.
or much easier:
len(each) == max(len(x) for x in myList)
or justeach == max(myList, key=len)
From the Python documentation itself, you can use
max
: