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
You can use a dict to collect the words:
results = {}
for word in words:
if len(word) not in results:
results[len(word)] = []
results[len(word)].append(word)
Next sort the dictionary by the keys, which are the lengths and print the words. This prints the longest words first, to reverse it, remove reverse=True:
for i in sorted(results.keys(), reverse=True):
print 'Number of words with length {}: {}'.format(i,len(results[i]))
for word in results[i]:
print word
To print only the shortest and longest:
shortest = sorted(results.keys())[0]
longest = sorted(results.keys(), reverse=True)[0]
print 'Shortest words:'
for word in results[shortest]:
print word
print 'Longest words:'
for word in results[longest]:
print word