Python sort list
last modified November 29, 2026 Python 3.15
In this article we show how to sort lists in Python.
Python has two tools for sorting: the sort method of lists, which
sorts a list in place, and the built-in sorted function, which
returns a new sorted list from any iterable. Both accept the same two optional
keyword arguments: key, a function that computes the value to sort
by, and reverse, which sorts in descending order.
Both use the same algorithm, Timsort (Powersort since Python 3.11), which is stable and very fast on data that is already partly ordered. The algorithm itself is explained in Python Timsort; other classic algorithms are compared in Python sorting algorithms.
sort and sorted
The sort method changes the list and returns None.
The sorted function leaves its argument unchanged.
words = ['forest', 'wood', 'tool', 'arc', 'sky', 'poor', 'cloud']
vals = [2, 1, 0, 3, 4, 6, 5, 7]
result = words.sort()
print(result)
print(words)
sorted_vals = sorted(vals)
print(sorted_vals)
print(vals)
print(sorted('falcon'))
print(sorted({5, 3, 9, 1}))
print(sorted((7, 2, 4)))
A common mistake is words = words.sort(), which replaces the list
with None. The sorted function accepts any iterable,
including strings, sets, and tuples, and always returns a list.
$ python sort_basic.py None ['arc', 'cloud', 'forest', 'poor', 'sky', 'tool', 'wood'] [0, 1, 2, 3, 4, 5, 6, 7] [2, 1, 0, 3, 4, 6, 5, 7] ['a', 'c', 'f', 'l', 'n', 'o'] [1, 3, 5, 9] [2, 4, 7]
Descending order
With reverse=True, the items are sorted from the largest to the
smallest.
vals = [7, 1, 12, 4, 9, 0, 3] vals.sort(reverse=True) print(vals) words = ['Sky', 'arc', 'Wood', 'cloud', 'Tool'] print(sorted(words)) print(sorted(words, reverse=True)) nums = [3, 1, 2] nums.reverse() print(nums)
Strings are compared by the code points of their characters. All uppercase
ASCII letters come before lowercase ones, so Wood precedes
arc. The reverse method is a different thing: it only
reverses the current order of the list without sorting it.
$ python descending.py [12, 9, 7, 4, 3, 1, 0] ['Sky', 'Tool', 'Wood', 'arc', 'cloud'] ['cloud', 'arc', 'Wood', 'Tool', 'Sky'] [2, 1, 3]
Key functions
The key argument takes a function of one argument. Python calls it
once for each item and sorts the items by the returned values. Built-in
functions and methods often serve as keys.
words = ['Sky', 'arc', 'Wood', 'cloud', 'Tool', 'up'] print(sorted(words, key=len)) print(sorted(words, key=str.lower)) print(sorted(words, key=len, reverse=True)) vals = [-7, 3, -1, 12, -4, 0] print(sorted(vals, key=abs)) prices = ['12.50', '9.99', '100.00', '25.10'] print(sorted(prices)) print(sorted(prices, key=float))
The len function sorts words by length, and str.lower
sorts them without regard to case. The key does not change the items:
abs orders numbers by their distance from zero, but the negative
signs stay. Number strings sort as text, so '100.00' comes first;
with key=float, they sort by their numeric value.
$ python key_builtin.py ['up', 'Sky', 'arc', 'Wood', 'Tool', 'cloud'] ['arc', 'cloud', 'Sky', 'Tool', 'up', 'Wood'] ['cloud', 'Wood', 'Tool', 'Sky', 'arc', 'up'] [0, -1, 3, -4, -7, 12] ['100.00', '12.50', '25.10', '9.99'] ['9.99', '12.50', '25.10', '100.00']
Custom key functions
A key function can be any function, defined with def or written
inline as a lambda expression.
names = ['John Doe', 'Lucia Smith', 'Roger Roe', 'Adam Brown',
'Tom Holland', 'Jane Doe']
def last_name(full):
return full.split()[-1]
print(sorted(names, key=last_name))
print(sorted(names, key=lambda n: n.split()[-1]))
points = [(4, 2), (1, 9), (3, -1), (0, 0), (2, 5)]
print(sorted(points))
print(sorted(points, key=lambda p: p[1]))
print(sorted(points, key=lambda p: p[0] ** 2 + p[1] ** 2))
The last_name function and the equivalent lambda return the last
word of a name. Tuples are compared item by item, so a plain
sorted(points) orders points by x. The other keys
order them by y and by the squared distance from the origin.
$ python key_lambda.py ['Adam Brown', 'John Doe', 'Jane Doe', 'Tom Holland', 'Roger Roe', 'Lucia Smith'] ['Adam Brown', 'John Doe', 'Jane Doe', 'Tom Holland', 'Roger Roe', 'Lucia Smith'] [(0, 0), (1, 9), (2, 5), (3, -1), (4, 2)] [(3, -1), (0, 0), (4, 2), (2, 5), (1, 9)] [(0, 0), (3, -1), (4, 2), (2, 5), (1, 9)]
Stable sorting
A sort is stable if items with equal keys keep their original order. Python's sort is guaranteed to be stable.
students = [('Patrick', 'B'), ('Lucia', 'A'), ('Robert', 'C'),
('Monika', 'A'), ('Adam', 'B'), ('Thomas', 'A'),
('Jana', 'C'), ('Kevin', 'B')]
by_grade = sorted(students, key=lambda s: s[1])
for name, grade in by_grade:
print(grade, name)
print()
by_name = sorted(students, key=lambda s: s[0])
by_grade_then_name = sorted(by_name, key=lambda s: s[1])
print([name for name, _ in by_grade_then_name])
Within each grade, the students appear in the order of the input list: Lucia, Monika, Thomas. Stability allows sorting in several passes. We first sort by the secondary key (the name) and then by the primary key (the grade); the second pass keeps the alphabetical order inside each grade.
$ python stable.py A Lucia A Monika A Thomas B Patrick B Adam B Kevin C Robert C Jana ['Lucia', 'Monika', 'Thomas', 'Adam', 'Kevin', 'Patrick', 'Jana', 'Robert']
Multiple sort criteria
To sort by several criteria in one pass, the key function returns a tuple. The tuples are compared by the first item, then by the second one, and so on.
employees = [
('Lucia', 'sales', 3100),
('John', 'it', 4200),
('Adam', 'sales', 2800),
('Jane', 'it', 4200),
('Peter', 'hr', 2600),
('Monika', 'it', 3900),
]
for e in sorted(employees, key=lambda e: (e[1], e[0])):
print(e)
print()
for e in sorted(employees, key=lambda e: (-e[2], e[0])):
print(e)
The first loop sorts the employees by department and then by name. The second
sorts them by salary in descending order and then by name in ascending order.
Negating a number reverses its order, so -e[2] puts the highest
salaries first while the names stay ascending.
$ python multi_key.py
('Peter', 'hr', 2600)
('Jane', 'it', 4200)
('John', 'it', 4200)
('Monika', 'it', 3900)
('Adam', 'sales', 2800)
('Lucia', 'sales', 3100)
('Jane', 'it', 4200)
('John', 'it', 4200)
('Monika', 'it', 3900)
('Lucia', 'sales', 3100)
('Adam', 'sales', 2800)
('Peter', 'hr', 2600)
Mixed directions for strings
Strings cannot be negated. To sort by one string ascending and another
descending, we use two stable passes with different reverse
values.
employees = [
('Lucia', 'sales', 3100),
('John', 'it', 4200),
('Adam', 'sales', 2800),
('Jane', 'it', 4200),
('Peter', 'hr', 2600),
('Monika', 'it', 3900),
]
result = sorted(employees, key=lambda e: e[0], reverse=True)
result.sort(key=lambda e: e[1])
for e in result:
print(e)
The first pass sorts by name in descending order, the second by department in ascending order. Thanks to stability, the names stay descending within each department. Another option is a comparison function converted with cmp_to_key.
$ python mixed_order.py
('Peter', 'hr', 2600)
('Monika', 'it', 3900)
('John', 'it', 4200)
('Jane', 'it', 4200)
('Lucia', 'sales', 3100)
('Adam', 'sales', 2800)
List of dictionaries
Records read from JSON or CSV files are often lists of dictionaries. The key function selects the values to sort by.
users = [
{'name': 'John Doe', 'occupation': 'gardener', 'born': 1987},
{'name': 'Adam Brown', 'occupation': 'driver', 'born': 1993},
{'name': 'Lucia Smith', 'occupation': 'teacher', 'born': 1979},
{'name': 'Roger Roe', 'occupation': 'driver', 'born': 1990},
{'name': 'Tom Holland', 'occupation': 'gardener', 'born': 1979},
]
for u in sorted(users, key=lambda u: u['born']):
print(u['born'], u['name'])
print()
def by_job_age(u):
return u['occupation'], -u['born']
for u in sorted(users, key=by_job_age):
print(f"{u['occupation']:9} {u['born']} {u['name']}")
The first loop sorts the users by year of birth. The by_job_age
function returns a tuple: users are grouped by occupation and, within each
occupation, the youngest comes first. The
operator module offers
itemgetter and attrgetter as ready-made key
functions for items and attributes.
$ python dicts.py 1979 Lucia Smith 1979 Tom Holland 1987 John Doe 1990 Roger Roe 1993 Adam Brown driver 1993 Adam Brown driver 1990 Roger Roe gardener 1987 John Doe gardener 1979 Tom Holland teacher 1979 Lucia Smith
None and mixed types
Sorting needs the < operator between the items. Values of
types that cannot be compared, such as None and integers, raise
a TypeError.
scores = [72, None, 95, 61, None, 88]
try:
scores.sort()
except TypeError as e:
print('error:', e)
print(sorted(scores, key=lambda s: (s is None, s or 0)))
print(sorted(scores, key=lambda s: (s is not None, s or 0)))
mixed = [10, '9', 8.5, '11']
try:
sorted(mixed)
except TypeError as e:
print('error:', e)
print(sorted(mixed, key=float))
The key (s is None, s or 0) puts the None values at
the end: False sorts before True. Inverting the test
moves them to the beginning. The second element replaces None
with zero, so the tuples never compare None with a number. A list
of numbers and number strings is sorted with a key that converts all items to
one type.
$ python none_values.py error: '<' not supported between instances of 'NoneType' and 'int' [61, 72, 88, 95, None, None] [None, None, 61, 72, 88, 95] error: '<' not supported between instances of 'str' and 'int' [8.5, '9', 10, '11']
Natural sort order
Text sorting puts img10.png before img2.png, because
the character 1 is smaller than 2. A natural sort
compares the numbers in strings by their values.
import re
files = ['img12.png', 'img10.png', 'IMG2.png', 'img1.png', 'img2.png',
'img100.png', 'readme.txt']
print(sorted(files))
def natural_key(text):
parts = re.split(r'(\d+)', text.lower())
return [int(p) if p.isdigit() else p for p in parts]
print(natural_key('img12.png'))
print(sorted(files, key=natural_key))
versions = ['1.10.0', '1.2.3', '1.2.10', '0.9']
print(sorted(versions))
print(sorted(versions, key=lambda v: [int(n) for n in v.split('.')]))
The natural_key function splits a string into text and digit
parts; the capturing group in the pattern keeps the digits in the result. The
digit parts become integers, and the list of parts is the key. Version strings
are sorted with a list of integers as the key.
$ python natural.py ['IMG2.png', 'img1.png', 'img10.png', 'img100.png', 'img12.png', 'img2.png', 'readme.txt'] ['img', 12, '.png'] ['img1.png', 'IMG2.png', 'img2.png', 'img10.png', 'img12.png', 'img100.png', 'readme.txt'] ['0.9', '1.10.0', '1.2.10', '1.2.3'] ['0.9', '1.2.3', '1.2.10', '1.10.0']
Locale-aware sorting
Sorting by code points puts accented letters after all ASCII letters. The
locale.strxfrm function transforms strings according to the
collation rules of a language.
import locale
words = ['zem', 'čučoriedka', 'Žaba', 'cesta', 'chlieb', 'auto', 'ďateľ',
'dub', 'Čaj', 'hora', 'ihla']
print(sorted(words))
locale.setlocale(locale.LC_COLLATE, 'sk_SK.UTF-8')
print(sorted(words, key=locale.strxfrm))
The plain sort places Čaj and Žaba at the end. With
the Slovak locale, č follows c, ž
follows z, and the letter ch comes after
h, as the Slovak alphabet requires. The locale must be installed
on the system; otherwise setlocale raises
locale.Error.
$ python localized.py ['auto', 'cesta', 'chlieb', 'dub', 'hora', 'ihla', 'zem', 'Čaj', 'čučoriedka', 'ďateľ', 'Žaba'] ['auto', 'cesta', 'Čaj', 'čučoriedka', 'ďateľ', 'dub', 'hora', 'chlieb', 'ihla', 'zem', 'Žaba']
Sorting dates
Dates in text form sort correctly only in the ISO 8601 format, where the year comes first. Other formats need a key that parses them.
from datetime import datetime
dates = ['21-Jun-2026', '3-Feb-2025', '1-Jan-2027', '18-Oct-2025',
'30-Jun-2026']
print(sorted(dates))
def parse(text):
return datetime.strptime(text, '%d-%b-%Y')
print(sorted(dates, key=parse))
iso = ['2026-06-21', '2025-02-03', '2027-01-01', '2025-10-18']
print(sorted(iso))
The parse function converts the text to a datetime
with strptime; the list keeps its original strings. ISO dates such
as 2026-06-21 sort correctly as plain strings. Parsing dates is
covered in Python parse dates.
$ python dates.py ['1-Jan-2027', '18-Oct-2025', '21-Jun-2026', '3-Feb-2025', '30-Jun-2026'] ['3-Feb-2025', '18-Oct-2025', '21-Jun-2026', '30-Jun-2026', '1-Jan-2027'] ['2025-02-03', '2025-10-18', '2026-06-21', '2027-01-01']
Custom order
Some values have an order that is neither alphabetical nor numeric, such as days of the week or priorities. The key looks up the position of a value in a list or a dictionary.
days = ['Fri', 'Mon', 'Sun', 'Wed', 'Mon', 'Tue', 'Sat']
week = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
print(sorted(days))
print(sorted(days, key=week.index))
priority = {'critical': 0, 'high': 1, 'normal': 2, 'low': 3}
tasks = [('backup', 'low'), ('patch server', 'critical'),
('write docs', 'normal'), ('fix login', 'high'),
('update deps', 'normal'), ('rotate keys', 'critical')]
for name, level in sorted(tasks, key=lambda t: priority[t[1]]):
print(f'{level:9} {name}')
The bound method week.index returns the position of a day in the
week. For the tasks, a dictionary maps each priority to a number, which is
faster than index for long lists. Tasks with the same priority stay
in their input order.
$ python custom_order.py ['Fri', 'Mon', 'Mon', 'Sat', 'Sun', 'Tue', 'Wed'] ['Mon', 'Mon', 'Tue', 'Wed', 'Fri', 'Sat', 'Sun'] critical patch server critical rotate keys high fix login normal write docs normal update deps low backup
Sorting cards
In this example we sort a poker hand by rank and by suit and rank. A card is a
two-character string such as T♥, with T for ten.
import random
RANKS = '23456789TJQKA'
SUITS = '♣♦♥♠'
deck = [r + s for s in SUITS for r in RANKS]
random.seed(7)
hand = random.sample(deck, 7)
print(hand)
def by_rank(card):
return RANKS.index(card[0])
def by_suit_rank(card):
return SUITS.index(card[1]), RANKS.index(card[0])
print(sorted(hand, key=by_rank, reverse=True))
print(sorted(hand, key=by_suit_rank))
The ranks and suits are strings in their playing order, so index
gives the value of a card. The by_suit_rank function returns a
tuple and groups the cards by suit. The random.seed call makes the
dealt hand repeatable.
$ python cards.py ['9♦', 'J♣', 'A♦', '4♠', '5♣', '6♣', 'T♥'] ['A♦', 'J♣', 'T♥', '9♦', '6♣', '5♣', '4♠'] ['5♣', '6♣', 'J♣', '9♦', 'A♦', 'T♥', '4♠']
Partial sorting
We do not need to sort a whole list to find its smallest or largest items. The
heapq and bisect modules help with partial order.
import bisect
import heapq
temps = [12.4, 18.1, 9.7, 21.3, 15.0, 7.2, 19.8, 11.5, 16.6]
print(sorted(temps)[:3])
print(heapq.nsmallest(3, temps))
print(heapq.nlargest(3, temps))
print(min(temps), max(temps))
cities = [('Oslo', 709_000), ('Rome', 2_749_000), ('Kyiv', 2_952_000),
('Bern', 146_000), ('Riga', 605_000)]
print(heapq.nlargest(2, cities, key=lambda c: c[1]))
print(min(cities, key=lambda c: c[1]))
scores = [41, 55, 63, 78, 90]
bisect.insort(scores, 70)
bisect.insort(scores, 35)
print(scores)
The heapq.nsmallest and nlargest functions return the
first items without sorting the rest; they are faster than
sorted when the list is long and only a few items are needed. They
and min and max accept a key. The
bisect.insort function inserts an item into a sorted list at the
right place, so the list stays sorted without calling sort
again.
$ python top_n.py
[7.2, 9.7, 11.5]
[7.2, 9.7, 11.5]
[21.3, 19.8, 18.1]
7.2 21.3
[('Kyiv', 2952000), ('Rome', 2749000)]
('Bern', 146000)
[35, 41, 55, 63, 70, 78, 90]
Source
Sorting techniques – Python documentation
list.sort – Python documentation
In this article we have sorted lists in Python with sort and
sorted, key functions, and stable multi-pass sorts. See also
Python cmp_to_key,
Python sorted builtin,
Python reverse, and
Python dictionary.
Author
List all Python tutorials.