How to find the length of an item in a list?

I am just starting with programming. I have a list of several lines, and now I need to print the largest (in length). Therefore, at first I just want to print the lengths of the elements. I tried things like this:

l = ("xxxxxxxxx", "yyyy","zz") for i in range(len(l): 

So how do I do this?

+4
source share
6 answers
 l = ("xxxxxxxxx", "yyyy","zz") print(max(l, key=len)) 

First of all, you do not have a list, you have a tuple. however, this code will work for any sequence; both lists and tuples are sequences (as well as strings, sets, etc.). Thus, the max function accepts the key argument, which is used to sort the iteration elements. Thus, of all the elements l , one that has the maximum length will be selected.

+14
source

To print the lengths of elements:

 elements = ["xxxxxx", "yyy", "z"] for element in elements: print len(element) 

I recommend you read some tutorials, for example http://docs.python.org/tutorial/

+4
source

just ask max according to length

print max(["qsf","qsqsdqsd","qs"], key = len)

+2
source
 >>> sorted(['longest','long','longer'],key=len)[-1] 'longest' 

UPDATE: SilentGhost's solution is much nicer.

+2
source

The following code will print the largest line in the set:

 l = ["abcdev", "xx","abcedeerer"] len_0 = len(l[0]) pos = 0 for i in range(0,len(l)): if len(l[i]) > len_0: pos = i print l[pos] 
+1
source

This code displays the len function above the list to get another list containing the length of each element.

 mylist = ("xxxxxxxxx", "yyyy","zz") len_mylist = map(len, mylist) max_position = len_mylist.index(max(len_mylist)) my_item = mylist[max_position] print('The largest item of my list is: ' + my_item) print('located at position: ' + str(max_position)) 
0
source

All Articles