Home > database >  How can I let python print out the elements in a list in alphabetical order?
How can I let python print out the elements in a list in alphabetical order?

Time:11-14

So I wrote this code to return every string in a list in the order of word length.

def sort_by_length(words: list[str]):
    return sorted(words, key=len)
print(sort_by_length(['this','is','a','test','for','sorting','by','length']))

and I get the output, which is

['a', 'is', 'by', 'for', 'this', 'test', 'length', 'sorting']

However, I want to change my code a bit so that if two or more strings has the same length, the code will return both the strings but in alphabetical order.

So like from the output that I get, I want it to be like:

['a', 'by', 'is', 'for', 'this', 'test', 'length', 'sorting']

What should I change?

CodePudding user response:

Use a key function that returns a tuple.

def sort_by_length(words: list[str]):
    return sorted(words, key=lambda x: (len(x), x))
  • Related