How to find length of an element in a list?
l = ("xxxxxxxxx", "yyyy","zz")
print(max(l, key=len))
First of all you don't have a list, you have a tuple. this code will work for any sequence, however; both lists and tuples are sequences (as well as strings, sets, etc). So, the max
function takes a key
argument, that is used to sort the elements of an iterable. So, from all elements of l
will be selected the one having the maximum length.
To print the lengths of the elements:
elements = ["xxxxxx", "yyy", "z"]
for element in elements:
print len(element)
I recommend you read some tutorial material, for instance http://docs.python.org/tutorial/
>>> sorted(['longest','long','longer'],key=len)[-1]
'longest'
UPDATE: SilentGhost's solution is a lot nicer.