0

Hi I am trying to print out the longest & shortest words in a list: Python

The list is = ["Deirdre", "Sandra", "Geraldine", "Keith", "Alyssa"]

i have no idea to where to start, I am new to this and this was on my worksheet this week i have tried a few things but just ant get it.

Thanks

Deirdre
  • 45
  • 2
  • 6
  • Possible duplicate of [Python's most efficient way to choose longest string in list?](http://stackoverflow.com/questions/873327/pythons-most-efficient-way-to-choose-longest-string-in-list) –  Mar 15 '17 at 13:32

3 Answers3

2

The min function has an optional parameter key that lets you specify a function to determine the "sorting value" of each item.

list_values = ["Deirdre", "Sandra", "Geraldine", "Keith", "Alyssa"]
print min(list_values, key=len)  # prints "Keith"
print max(list_values, key=len)  # prints "Geraldine"
Mohsin Aljiwala
  • 2,457
  • 2
  • 23
  • 30
0

You can use python's built-in min and max functions:

l = ["Deirdre", "Sandra", "Geraldine", "Keith", "Alyssa"]
shortest_name = min(l, key=len)
longest_name = max(l, key=len)
print(shortest_name, longest_name)
Nynq
  • 26
  • 2
0

You can use the key parameter of the function min or max like the following :

myList = ["Deirdre", "Sandra", "Geraldine", "Keith", "Alyssa"]
minName = min(l, key=len)
maxName = max(l, key=len)
print "shortest name: "
print(minName)
print "longest name: "
print(maxName)
Loay Ashmawy
  • 677
  • 1
  • 7
  • 26