Problem: Given a list of strings. Sort the list of strings in alphabetical order.
['Frank', 'Alice', 'Bob'] --> ['Alice', 'Bob', 'Frank']
Solution: Use the list.sort() method without argument to solve the list in lexicographical order which is a generalization of alphabetical order (also applies to the second, third, … characters).
lst = ['Frank', 'Alice', 'Bob'] lst.sort() print(lst) # ['Alice', 'Bob', 'Frank']
Try It Yourself:
Python List Sort Alphabetically Case Insensitive
The problem with the default list.sort() or sorted(list) method is that they consider capitalization. This way, it can lead to strange sortings like this:
lst = ['ab', 'Ac', 'ad'] lst.sort() print(lst) # ['Ac', 'ab', 'ad']
Intuitively, you would expect the string
'ab' to occur before
To ignore the capitalization, you can simply call the
x.lower() method on each element
x before sorting the list.
However, my preferred method is to use the key argument to accomplish the same thing in a single line of code:
lst = ['ab', 'Ac', 'ad'] lst.sort(key=lambda x: x.lower()) print(lst) # ['ab', 'Ac', 'ad']
If you like one-liners, you’ll love my new book “Python One-Liners” with NoStarch Press (Amazon Link).
Python List Sort Alphabetically Reverse
You can reverse the order of the list by using the reverse keyword. Set
reverse=False to sort in ascending order and set
reverse=True to sort in descending order.
lst = ['Frank', 'Alice', 'Bob'] lst.sort(reverse=False) print(lst) # ['Alice', 'Bob', 'Frank'] lst.sort(reverse=True) print(lst) # ['Frank', 'Bob', 'Alice']
Python List Sort Alphabetically and Numerically
Problem: You’ve got a list of strings. Each strings contains a number. You want the numbers to sort numerically (e.g. 100 comes after 20, not before) but the characters to sort alphabetically (e.g.,
'c' comes before
['alice 100', 'alice 20', 'bob 99'] --> ['alice 20', 'alice 100', 'bob 99'
Naive Solution (doesn’t work): Use the list.sort() method to sort the list alphabetically:
lst = ['alice 100', 'alice 20', 'bob 99'] lst.sort() print(lst) # ['alice 100', 'alice 20', 'bob 99']
Because the number 100 comes before 20 in an alphabetical order, the string
'alice 100' is placed before
Solution: I found this code on StackOverflow that nicely demonstrates how to do this:
import re def sorted_nicely(l): """ Sort the given iterable in the way that humans expect.""" convert = lambda text: int(text) if text.isdigit() else text alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)] l.sort(key = alphanum_key) lst = ['alice 100', 'alice 20', 'bob 99'] sorted_nicely(lst) print(lst) # ['alice 20', 'alice 100', 'bob 99']
The idea is to differentiate characters and numbers and use them as the basis of comparison for the sort routine.
Where to Go From Here?
list.sort() method sorts the list elements in place in an ascending manner. To customize the default sorting behavior, use the optional
key argument by passing a function that returns a comparable value for each element in the list. With the optional Boolean
reverse argument, you can switch from ascending (
reverse=False) to descending order (
If you keep struggling with those basic Python commands and you feel stuck in your learning progress, I’ve got something for you: Python One-Liners (Amazon Link).
In the book, I’ll give you a thorough overview of critical computer science topics such as machine learning, regular expression, data science, NumPy, and Python basics—all in a single line of Python code!
OFFICIAL BOOK DESCRIPTION: Python One-Liners will show readers how to perform useful tasks with one line of Python code. Following a brief Python refresher, the book covers essential advanced topics like slicing, list comprehension, broadcasting, lambda functions, algorithms, regular expressions, neural networks, logistic regression and more. Each of the 50 book sections introduces a problem to solve, walks the reader through the skills necessary to solve that problem, then provides a concise one-liner Python solution with a detailed explanation.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.