Python: How can I get all the items in a list to the longest item?

I have a list like

l = ['abc34','def987','ghij','klmno','pqrstuvwxyz1234567','98765','43','210abc']

How can I get all the items in the list before the longest item appears, and not those that come after?

+2
source share
2 answers

It works:

lst = ['abc34','def987','ghij','klmno','pqrstuvwxyz1234567','98765','43','210abc']
idx, maxLenStr = max(enumerate(lst), key=lambda x:len(x[1]))
sublist = lst[:idx]

It only iterates through the list once to determine the maximum length, while using max()and then index()repeating it twice across all elements. It also stores the string with the maximum length in maxLenStrand the index where it was found in idx, just in case.

+3
source

This is one way:

l = ['abc34','def987','ghij','klmno','pqrstuvwxyz1234567','98765','43','210abc']
new_list = l[:l.index(max(l, key=len))]
+9
source

All Articles