Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 = ['abc','abcdef','abcd']  for each in mylist:     if condition1:         do_something()     elif ___________________: #else if each is the longest string contained in mylist:         do_something_else() 

Surely there's a simple list comprehension that's short and elegant that I'm overlooking?

like image 979
user104997 Avatar asked May 16 '09 21:05

user104997


People also ask

What is the maximum length of a list in Python?

According to the source code, the maximum size of a list is PY_SSIZE_T_MAX/sizeof(PyObject*) . On a regular 32bit system, this is (4294967295 / 2) / 4 or 536870912. Therefore the maximum size of a python list on a 32 bit system is 536,870,912 elements.


1 Answers

From the Python documentation itself, you can use max:

>>> mylist = ['123','123456','1234'] >>> print max(mylist, key=len) 123456 
like image 91
Paolo Bergantino Avatar answered Oct 19 '22 18:10

Paolo Bergantino