-2

Possible Duplicate:
how to sort by length of string followed by alphabetical order?

I want to create a program that prints the word in a list in order of shortest to longest character count. For example:

["My", "turtle", "is", "old"]

would output:

"My"
"is"
"old"
"turtle"

Is there any simple way to do this? I have so far:

message = "My turtle is old"
message = message.split(" ")
Community
  • 1
  • 1
JSW189
  • 6,267
  • 11
  • 44
  • 72
  • 2
    How is that at all representative of "in order of longest to shortest character count"? – mechanical_meat Mar 28 '12 at 16:37
  • 1
    possible duplicate of [how to sort by length of string followed by alphabetical order?](http://stackoverflow.com/questions/4659524/how-to-sort-by-length-of-string-followed-by-alphabetical-order) and even more exact [Sorting Python list based on the length of the string](http://stackoverflow.com/questions/2587402/sorting-python-list-based-on-the-length-of-the-string) which I found by googling "python sort by length". – agf Mar 28 '12 at 16:40
  • 1
    How come the title is shortest to longest and the question is from longest to shortest ? Make up your mind :D – Kien Truong Mar 28 '12 at 16:43

2 Answers2

4
l = ["My", "turtle", "is", "old"]
l.sort(key=len, reverse=True)
# -> ['turtle', 'old', 'My', 'is']

You might wish to review the Python wiki on the subject: http://wiki.python.org/moin/HowTo/Sorting

mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
0

Sort the input by length using the key keyword for .sort():

l = ["My", "turtle", "is", "old"]
l.sort(key=len)

for i in l:
  print i
Blender
  • 289,723
  • 53
  • 439
  • 496