I need to go through a list and print the longest words in it. I can do this for just one word, but can\'t figure out how to print more than one, if there are two words
Firstly, don't ever use list
as a variable name as it will override the built in type and could cause trouble later on.
You could do this for the longest words:
for i in lst:
if len(i) == max(lst, key=len):
print(i)
And for the shortest words:
for i in lst:
if len(i) == min(lst, key=len):
print(i)
The first code prints the strings which have the same length as the longest string. The second does the same, but with the shortest strings.
A small optimisation would be to precalculate the max/min length before the loop, so you don't need to recalculate it every time.
maxLen = max(lst, key=len)
for i in lst:
if len(i) == maxLen:
print(i)
The same can be done for the other loop.