1. Home
  2. Blog
  3. Software Development

Software Development

Python Sort List: sort() vs sorted(), key, reverse and 9 Tested Examples

To sort a list in Python, call list.sort() to change it in place or sorted() to get a new sorted copy. This guide shows when to use each, how key= and reverse= work, and how to sort by several fields, ignore case, handle None and sort file names naturally.

9 min read
Python sort list: sort() vs sorted() with examples

Key takeaways

  • Python sort list in one line: items.sort() changes the list and returns None; sorted(items) returns a new list.
  • key= decides what to compare (length, lowercase, a field) and reverse=True flips the order.
  • Python sorting is stable, so you can sort by several fields with a tuple key or with two passes.
  • Sorting 100,000 random floats took about 15 ms in our test; an already sorted list took under 1 ms.

Sorting looks trivial until you need to sort names without caring about capitals, order employees by age and then name, or put file2 before file10. This Python sort list guide covers all of it with code we ran on Python 3.13.6; every output shown is copied from that run.

Quick answer

nums = [5, 2, 9, 1]
nums.sort()                 # in place
print(nums)                 # [1, 2, 5, 9]

a = [5, 2, 9, 1]
b = sorted(a)               # new list
print(b, a)                 # [1, 2, 5, 9] [5, 2, 9, 1]

Use sort() when you no longer need the original order. Use sorted() when you do, or when the data is not a list at all.

sort() vs sorted(): the real differences

Feature list.sort() sorted()
Changes the original Yes No
Returns None A new list
Works on Lists only Any iterable: tuple, string, set, dict, generator
Memory No copy Makes a copy
key and reverse Yes Yes

Because sorted() accepts any iterable, it is the one you use for other types. In our run, sorted("banana") gave ['a', 'a', 'a', 'b', 'n', 'n'], sorted({"b": 1, "a": 2}) gave the keys ['a', 'b'], and sorted((3, 1, 2)) returned a list, not a tuple. If you are unsure which container to use, see our list vs tuple vs set guide.

Sort in descending order

nums.sort(reverse=True)
desc = sorted(nums, reverse=True)

reverse=True sorts largest first. It is not the same as list.reverse(), which simply flips the current order without sorting anything.

The key argument

key takes a function that is called once per item; the list is sorted by the results. The items themselves are not changed.

1. Ignore upper and lower case

words = ["banana", "Cherry", "apple"]
print(sorted(words))                  # ['Cherry', 'apple', 'banana']
print(sorted(words, key=str.lower))   # ['apple', 'banana', 'Cherry']

Plain sorting compares character codes, and every capital letter comes before every lowercase one, so “Cherry” jumped to the front. key=str.lower compares the lowercase versions.

2. Sort by length

words = ["banana", "Apple", "cherry", "apple"]
print(sorted(words, key=len))                 # ['Apple', 'apple', 'banana', 'cherry']
print(sorted(words, key=len, reverse=True))   # ['banana', 'cherry', 'Apple', 'apple']

3. Sort records by a field

from operator import itemgetter
people = [("Asha", 31, "Pune"), ("Ravi", 25, "Delhi"),
          ("Li", 31, "Delhi"), ("Sam", 25, "Pune")]
print(sorted(people, key=itemgetter(1)))
[('Ravi', 25, 'Delhi'), ('Sam', 25, 'Pune'), ('Asha', 31, 'Pune'), ('Li', 31, 'Delhi')]

itemgetter(1) is a fast, readable alternative to lambda p: p[1]. For objects, attrgetter("age") does the same for attributes. Lambdas are explained in our Python lambda functions guide.

Sort by several fields

4. Tuple key: age descending, then name

print(sorted(people, key=lambda p: (-p[1], p[0])))
[('Asha', 31, 'Pune'), ('Li', 31, 'Delhi'), ('Ravi', 25, 'Delhi'), ('Sam', 25, 'Pune')]

Tuples compare item by item, so the key sorts by the first value and breaks ties with the second. Negating a number reverses just that field.

Stable sorting: the two-pass trick

Python’s sort is stable: items with equal keys keep their existing order. That lets you sort by the secondary field first, then the primary one, which is useful when a field cannot be negated, such as text you want descending.

5. City, then name

s = sorted(people, key=itemgetter(0))   # secondary: name
s = sorted(s, key=itemgetter(2))        # primary: city
print(s)
[('Li', 31, 'Delhi'), ('Ravi', 25, 'Delhi'), ('Asha', 31, 'Pune'), ('Sam', 25, 'Pune')]

Tip: with two passes, each pass can use its own reverse=True. That is the cleanest way to sort, for example, city A to Z but score high to low.

Sort a dictionary by value

6. Items ordered by value

scores = {"x": 3, "y": 1, "z": 2}
print(sorted(scores.items(), key=itemgetter(1)))   # [('y', 1), ('z', 2), ('x', 3)]
ranked = dict(sorted(scores.items(), key=itemgetter(1), reverse=True))

Dictionaries keep insertion order, so building a new dict from sorted items gives you a sorted dictionary. Our Python dictionary guide covers more dict patterns.

Tricky data

7. Mixed types fail

sorted([3, "a", 1])
TypeError: '<' not supported between instances of 'str' and 'int'

Python 3 refuses to guess how a number compares with text. Clean or convert the data first.

8. Put None values last

print(sorted([3, None, 1], key=lambda v: (v is None, v)))   # [1, 3, None]

The key puts a False or True flag first, so all real values sort before the None values, which are never compared with numbers.

9. Natural sort for file names

files = ["file10", "file2", "file1"]
print(sorted(files))                               # ['file1', 'file10', 'file2']
print(sorted(files, key=lambda s: int(s[4:])))     # ['file1', 'file2', 'file10']

Text sorting compares character by character, so “file10” comes before “file2”. Extract the number for the key. For messy real names, use a regular expression to pull out digits; see our Python regex guide.

How fast is Python sorting?

We timed 100,000 random floats, averaging 20 runs:

Operation Time per sort
Copy then list.sort() 14.8 ms
sorted(data) 15.2 ms
sorted() on already sorted data 0.9 ms

Both functions use the same algorithm, so speed is not a reason to choose one over the other. The algorithm detects runs of already ordered data, which is why the presorted list was about 16 times faster. If you only need the top few items, heapq.nlargest(3, data) avoids sorting everything; in our run it returned [9, 7, 5] from [5, 2, 9, 1, 7].

Common mistakes

  • new = old.sort(): sort() returns None, so new is None. We printed it to confirm. Use sorted(old).
  • Sorting a tuple or string with .sort(): those types have no sort method. Use sorted().
  • Calling the key function: write key=str.lower, not key=str.lower().
  • Expecting reverse() to sort: it only flips the order.
  • Comparing mixed types: clean the data or supply a key that returns comparable values.

Python sort list cheat sheet

Goal Code
Sort in place items.sort()
New sorted list sorted(items)
Descending sorted(items, reverse=True)
Ignore case sorted(words, key=str.lower)
By field sorted(rows, key=itemgetter(1))
Two fields, one reversed key=lambda r: (-r.age, r.name)
Dict by value sorted(d.items(), key=itemgetter(1))
None last key=lambda v: (v is None, v)
Top N only heapq.nlargest(n, items)

Sorting objects and dataclasses

Real programs often sort objects rather than tuples. attrgetter reads attributes the way itemgetter reads positions, and it accepts several names for multi-field sorts:

from dataclasses import dataclass
from operator import attrgetter

@dataclass
class Employee:
    name: str
    dept: str
    salary: int

staff = [Employee("Asha", "QA", 90), Employee("Ravi", "Dev", 120),
         Employee("Li", "QA", 110), Employee("Sam", "Dev", 120)]

print([e.name for e in sorted(staff, key=attrgetter("salary"), reverse=True)])
print([e.name for e in sorted(staff, key=attrgetter("dept", "name"))])
['Ravi', 'Sam', 'Li', 'Asha']
['Ravi', 'Sam', 'Asha', 'Li']

Ravi and Sam tie on salary, and stability kept them in their original order. If a type has one natural order, let the class define it. A dataclass with order=True compares its fields from left to right:

@dataclass(order=True)
class Version:
    major: int
    minor: int
    patch: int

print(sorted([Version(1, 10, 0), Version(1, 2, 3), Version(1, 2, 0)]))
[Version(major=1, minor=2, patch=0), Version(major=1, minor=2, patch=3), Version(major=1, minor=10, patch=0)]

Version 1.10.0 correctly came last, which plain string sorting of “1.10.0” and “1.2.3” would get wrong. Dataclasses are covered in depth in our Python dataclasses guide.

The same key trick beyond sorting

Once you understand key=, you can use it in several other built-ins that pick items by a rule, often avoiding a full sort:

words = ["banana", "Cherry", "apple", "fig"]
print(max(words, key=len))                 # banana
print(min(words, key=len))                 # fig
print(min(words, key=str.lower))           # apple
print(heapq.nsmallest(2, words, key=len))  # ['fig', 'apple']

max() and min() scan the list once, which is cheaper than sorting just to take the first item. heapq.nsmallest and nlargest return the top few. itertools.groupby also works with a key, but it only groups neighbouring items, so sort by the same key first; our itertools guide shows the pattern.

Final thoughts

Python sort list tasks come down to two choices: sort() or sorted(), and what to put in key. Pick sorted() when you need the original or have a non-list, use a key function or tuple for anything beyond plain values, and lean on stability for multi-field sorts. For records with many fields, a dataclass with attrgetter keeps sort code readable.

Frequently asked questions

What is the difference between sort() and sorted() in Python?

list.sort() sorts the list in place and returns None. sorted() works on any iterable and returns a new sorted list, leaving the original unchanged.

How do I sort a list in descending order in Python?

Pass reverse=True, as in items.sort(reverse=True) or sorted(items, reverse=True).

How do I sort a list of tuples by the second element?

Use a key: sorted(rows, key=lambda r: r[1]) or the faster sorted(rows, key=itemgetter(1)) from the operator module.

Why does my sorted list print None?

You probably wrote new_list = old_list.sort(). The sort method changes the list in place and returns None; use sorted(old_list) to get a new list.

Is Python sorting stable?

Yes. Items that compare equal keep their original order, which lets you sort by several fields with two passes.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
Software Development

HTTP Methods Explained: GET, POST, PUT, PATCH, DELETE, Tested on a Live Server

HTTP methods explained with a small server we ran: GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS, safe vs idempotent,…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Databases & SQL

SQL ORDER BY Multiple Columns: ASC, DESC, NULLS LAST, Case and Custom Order

SQL ORDER BY with multiple columns explained with tested queries: mixed ASC and DESC, tie-breakers, NULLS FIRST and LAST, case-insensitive…

Read article →
Databases & SQL

SQL Running Total: SUM OVER, Per-Group Totals, Moving Sums and the RANGE Trap

How to calculate a SQL running total with SUM() OVER: per-group totals, daily cumulative sums, moving sums, percent of total,…

Read article →
Software Development

JavaScript Sort Array: Numbers, Objects, Strings and Why 10 Comes Before 5

How to sort an array in JavaScript correctly: numbers with a compare function, objects by one or more fields, strings…

Read article →
Software Development

Python String Methods: Cheat Sheet, Real Examples and the strip() Trap

Python string methods with tested examples: split, join, strip, replace, find, startswith, is-methods, casefold, partition and translate, plus the strip()…

Read article →
Software Development

Python zip() Explained: Loop Two Lists at Once, Unzip, strict=True and Traps

Python zip() pairs items from several lists in one loop. Tested examples for dicts, unzipping with *, strict=True, zip_longest, sliding…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
Software Development

UTF-8 Encoding Explained: How Text Becomes Bytes and How to Fix Garbled Text

UTF-8 encoding explained with byte-level examples we ran in Python: how characters become 1 to 4 bytes, why café turns…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Databases & SQL

Delete Duplicate Rows in SQL: 5 Safe Methods, Tested Step by Step

How to delete duplicate rows in SQL safely: find them, preview them, then remove them with ROW_NUMBER, MIN(id), EXISTS, rowid…

Read article →
Databases & SQL

SQL RANK vs DENSE_RANK vs ROW_NUMBER: Differences with Tested Examples

SQL RANK vs DENSE_RANK vs ROW_NUMBER in one table: how each handles ties, top-N per group, the second-highest salary trap…

Read article →
Software Development

JavaScript Optional Chaining (?.) Explained: 8 Examples, ?? Defaults and Traps

JavaScript optional chaining stops “Cannot read properties of undefined” errors. 8 tested examples for properties, arrays and methods, ?? vs…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Software Testing

Pairwise Testing Explained: How All-Pairs Cuts 216 Tests to 13, Tested

Pairwise testing explained with a generator we ran in Python 3.13: a checkout with 216 combinations covered by 13 tests,…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →
Databases & SQL

SQL COALESCE Explained: Defaults, NULLIF, IFNULL vs ISNULL and Traps, Tested

SQL COALESCE explained with queries we ran in SQLite 3.50: first non-null values, empty strings, NULL in maths, NULLIF for…

Read article →
Databases & SQL

SQL Self Join Explained: Employee-Manager, Pairs and Row Comparisons, Tested

SQL self join explained with queries we ran in SQLite 3.50: employee and manager, earning more than the manager, unique…

Read article →
Artificial Intelligence

LLM Context Window Explained: Tokens, Limits and How to Fit More, Measured

The LLM context window explained with token counts we measured using tiktoken: words vs tokens for prose, code and Hindi,…

Read article →
DevOps

Git Cherry-Pick Explained: Copy the Commit You Need, Safely, Tested

Git cherry-pick explained with commands we ran in Git 2.56: copying a hotfix to a release branch, new hashes and…

Read article →
Test Automation

Snapshot Testing Explained: How It Works, When It Helps and When It Hurts

Snapshot testing explained with a pytest and syrupy demo we ran: creating snapshots, reading the diff after a code change,…

Read article →
Software Testing

Mutation Testing Explained: Why 100% Coverage Still Missed Our Bug

Mutation testing explained with a small mutation tool we built and ran: 14 mutants, a test suite with 100% line…

Read article →
Artificial Intelligence

Prompt Injection Explained: How AI Apps Get Tricked and How to Defend Them

Prompt injection explained for builders: direct and indirect attacks, why keyword filters fail (our test blocked 1 of 4), and…

Read article →
DevOps

DNS Records Explained: A, AAAA, CNAME, MX, TXT and TTL With Real Lookups

DNS records explained with lookups we ran: how resolution works, A and AAAA, CNAME rules, MX and null MX, TXT…

Read article →
DevOps

Feature Flags Explained: Safe Releases, Gradual Rollouts and Flag Hygiene

Feature flags explained with a rollout simulation we ran: flag types, percentage rollouts with stable hashing, kill switches, allow lists,…

Read article →
Test Automation

Test Data Generation With Python Faker: Realistic, Repeatable and Safe Data

Test data generation with Python Faker, run and measured: seeding for repeatable data, locales, unique values, domain-shaped records, edge cases…

Read article →
Software Testing

Shift-Left Testing Explained: Find Bugs Earlier Without Slowing the Team

Shift-left testing explained: what it means, why early defects are cheaper, practices from requirement reviews to CI checks, the tester's…

Read article →
Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →