Sort a list of strings in Python
This post will discuss how to sort a list of strings in Python.
1. Using sort() function
The standard solution to sort a list of strings in Python is using the sort() function. This function sorts the list in-place and results in a stable sort.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': words = ['D', 'A', 'C', 'B'] words.sort() print(words) # ['A', 'B', 'C', 'D'] |
The sort() function accepts the reverse argument, which takes a boolean value. When true, the list is sorted in reverse order.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': words = ['D', 'A', 'C', 'B'] words.sort(reverse=True) print(words) # ['D', 'C', 'B', 'A'] |
2. Using sorted() function
The list.sort() function modifies the original list as it uses an in-place sorting algorithm. To get a new, sorted copy of a list without changing the original list, use the sorted() built-in function.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': words = ['D', 'A', 'C', 'B'] sortedList = sorted(words) print(sortedList) # ['A', 'B', 'C', 'D'] |
To sort a list in reverse order, specify the reverse argument as True.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': words = ['D', 'A', 'C', 'B'] sortedListDesc = sorted(words, reverse=True) print(sortedListDesc) # ['D', 'C', 'B', 'A'] |
That’s all about sorting a list of strings in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)