How to sort list of strings based on alphabetical order?

Question:

For example, I have a list of strings:

``````How to make pancakes from scratch
How to change a tire on a car
How to install a new showerhead
How to change clothes
``````

I want to it be sorted as in the new list:

``````How to change a tire on a car
How to change clothes
How to install a new showerhead
How to make pancakes from scratch
``````

In each of these strings, "How to" are the same, it has to look at the next character, and then get the order ‘c/i/m’, then ‘a/c’ etc.

``````L = ['How to make pancakes from scratch',
'How to change a tire on a car',
'How to install a new showerhead',
'How to change clothes']
``````

I can sort one string in alphabetical order. But how to extend the logic to a list of strings?

``````L = ['How to make pancakes from scratch',
'How to change a tire on a car',
'How to install a new showerhead',
'How to change clothes']

sorted_list = sorted(L)
``````

If we then use `print(sorted_list)` the output is:

``````['How to change a tire on a car', 'How to change clothes', 'How to install a new showerhead', 'How to make pancakes from scratch']
``````

The sorted() function sorts the list in ascending order, which means that it sorts the strings in alphabetical order. If you want to sort the list in descending order, you can pass the reverse=True argument to the sorted() function:

``````sorted_list = sorted(L, reverse=True)
print(sorted_list)
``````

Hope it works

Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.