How to Sort List in Python 3 Examples
This short tutorial will show you how to sort lists in Python.
Several different sorting techniques will be shown: including basic, natural, case insensitive, alphabetically.
Data used in this article:
import calendar
days = list(calendar.day_name)
the unsorted list is:
['Friday', 'Monday', 'Saturday', 'Sunday', 'Thursday', 'Tuesday', 'Wednesday']
1. Python sort list alphabetically with .sort()
Here's how you can sort a list alphabetically with Python. We are going to use method sort():
days.sort()
days
result:
['Friday', 'Monday', 'Saturday', 'Sunday', 'Thursday', 'Tuesday', 'Wednesday']
Note that this method works on the data structure. No need to assign a new variable . Default sorting is ascending. In order to change the order parameter reverse
can be used:
days.sort(reverse=True)
days
result:
['Wednesday', 'Tuesday', 'Thursday', 'Sunday', 'Saturday', 'Monday', 'Friday']
2. Python sort list alphabetically with sorted()
To sort a list in Python without changing the list itself - use sorted().
sorted(days)
result:
['Friday', 'Monday', 'Saturday', 'Sunday', 'Thursday', 'Tuesday', 'Wednesday']
But the list itself is unchanged:
days
result:
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
3. Python natural sort of list
Natural sort is closer to human perception for order. Let's illustrate it with a simple example of days. Let's have a list of days:
days = ['day5', 'Day1', 'day7', 'DAY9', 'day10', 'day_11']
Using the previous sorting methods will give result:
['DAY9', 'Day1', 'day10', 'day5', 'day7', 'day_11']
which is not what is the natural order of the days. As a human I would expect:
['Day1', 'day5', 'day7', 'DAY9', 'day10', 'day_11']
In order to achieve this we can use the Python package: natsort.
Method natsorted
will be used in combination with parameters: key
or alg
:
from natsort import natsorted, ns
natsorted(days, key=lambda y: y.lower())
You can change the algorithm by parameter alg
:
natsorted(days, alg=ns.IGNORECASE)
which will produce the same output.
If no parameter is used:
natsorted(days)
output:
['DAY9', 'Day1', 'day5', 'day7', 'day10', 'day_11']