Python sorted() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
Built-in

Definition

In Python, sorted(iterable) returns a new list with the items in ascending order and leaves the original untouched. It works on any iterable: lists, tuples, strings, sets, dicts (their keys), and generators.

key is a function applied to each item to decide the order, and reverse=True sorts in descending order. The sort is stable: items that compare equal keep their original relative order, which lets you sort by several fields step by step.

sorted() is a built-in function: it lives in the builtins module, so it is always available without an import.

Syntax

Pass an iterable; add key and reverse by keyword.

python
result = sorted(iterable)
result = sorted(iterable, key=len, reverse=True)
CallWhat it does
sorted([3, 1, 2])Returns [1, 2, 3].
sorted(words, key=str.lower)Alphabetical, ignoring case.
sorted(nums, reverse=True)Largest first.
sorted(d, key=d.get)Dict keys ordered by their values.

list.sort() sorts a list in place and returns None; sorted() returns a new list and works on any iterable.

Library declarations
python
sorted(iterable, /, *, key=None, reverse=False)

Parameters

ParameterDescription
iterableRequired. Any iterable of mutually comparable items.
keyOptional, keyword-only. A one-argument function whose result is used for comparing.
reverseOptional, keyword-only. True for descending order. Default False.

Return Value

Return ValueDescription
listA new list in sorted order.

Python Examples

Example 1 — Sort Numbers, Text, and Dict Keys

Sort ascending and descending, and confirm the original list is unchanged.

python
numbers = [5, 2, 9, 1]

print(sorted(numbers))
print(sorted(numbers, reverse=True))
print(numbers)
print(sorted("python"))
print(sorted({"b": 1, "a": 2}))

How It Works

  1. New list. sorted(numbers) returns a sorted copy; numbers keeps its order.
  2. Descending. reverse=True puts the largest first.
  3. Strings become letter lists. Sorting "python" returns its characters in alphabetical order.
  4. Dicts sort their keys. Iterating a dict yields keys, so the result is ['a', 'b'].

Example 2 — Sort by Case-Insensitive Text, Length, and Field

Compare the default order with three different key functions.

python
words = ["banana", "apple", "Cherry", "date"]
print(sorted(words))
print(sorted(words, key=str.lower))
print(sorted(words, key=len))

people = [("Ana", 31), ("Ben", 25), ("Cy", 31)]
print(sorted(people, key=lambda p: p[1]))

How It Works

  1. Default is code point order. Capital C (67) sorts before every lowercase letter.
  2. Ignore case. key=str.lower compares lowercase copies and returns the original words.
  3. By length, stably. banana and Cherry both have 6 letters and stay in their original order.
  4. By a field. The lambda sorts people by age; Ana and Cy tie at 31 and keep their order.

Example 3 — Sort by Several Fields and Mixed Types

Sort by grade, then by score descending, use operator.itemgetter, and see the error for mixed types.

python
from operator import itemgetter

scores = [("Ana", "B", 88), ("Ben", "A", 92), ("Cy", "B", 75), ("Dee", "A", 92)]

by_grade_then_score = sorted(scores, key=lambda s: (s[1], -s[2]))
for name, grade, score in by_grade_then_score:
    print(grade, score, name)

print([s[0] for s in sorted(scores, key=itemgetter(2), reverse=True)])

try:
    sorted([3, "a", 1])
except TypeError:
    print("cannot compare int and str")

How It Works

  1. Tuple keys. (grade, -score) sorts by grade first, then by score from high to low.
  2. Ties stay stable. Ben and Dee both have A and 92, so they keep their input order.
  3. itemgetter. itemgetter(2) is a fast key that reads index 2; reverse=True keeps ties in input order too.
  4. Mixed types fail. Python 3 refuses to compare 3 with "a" and raises TypeError.

Frequently Asked Questions

sorted() returns a new list from any iterable. list.sort() changes the list in place and returns None.
Pass reverse=True: sorted(values, reverse=True).
Use a key: sorted(rows, key=lambda r: r["age"]) or key=operator.itemgetter("age").
Yes. Equal items keep their original relative order, so you can sort by a secondary key first and the primary key second.
Use key=str.lower, or key=str.casefold for full Unicode case folding.

Next: staticmethod()

Define a method that receives neither self nor cls.

staticmethod() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

7 people found this page helpful