Python sorted() Function

Learn how Python sorted() works with examples. Understand the difference between sort() and sorted(), sort lists, tuples, strings, dictionaries, use key functions, reverse=True, lambda, and custom sorting.

Published

Updated

Read time 5 min read

Reviewed byDeepak Prasad

Python sorted() Function

The sorted() function returns a new sorted list from any iterable. It works with lists, tuples, strings, dictionaries, sets, and other iterable objects. Use it when you want sorted output without changing the original data.

Tested on: Python 3.13.3; kernel 6.14.0-37-generic.


Quick answer: sort vs sorted in Python

Use sorted(data) when you want a new sorted list. Use data.sort() only when data is a list and you want to modify it in place.

python
numbers = [3, 1, 4, 1, 5]

print(sorted(numbers))
print(numbers)

numbers.sort()
print(numbers)
Output

The first print shows [1, 1, 3, 4, 5]. The second still shows the original order because sorted() does not change the list. After sort(), the list itself is sorted in place.


Python sorted() quick reference

Task Use
Sort a list and return new list sorted(numbers)
Sort list in place numbers.sort()
Sort descending sorted(numbers, reverse=True)
Sort strings alphabetically sorted(words)
Sort case-insensitively sorted(words, key=str.lower)
Sort by length sorted(words, key=len)
Sort tuple sorted(my_tuple)
Sort dictionary keys sorted(my_dict)
Sort dictionary items by key sorted(my_dict.items())
Sort dictionary items by value sorted(my_dict.items(), key=lambda item: item[1])
Sort list of dictionaries sorted(data, key=lambda item: item["field"])
Sort list of lists sorted(data, key=lambda row: row[1])

For deeper list-only or dictionary-only examples, see Python sort list, sort dictionary by key, and sort dictionary by value.


What is sorted() in Python?

sorted() is a built-in function. It accepts any iterable, returns a new list, and does not modify the original object. You can control sorting with key and reverse.

Even when you sort a tuple or string, the result is always a list.


Python sorted() syntax

Syntax: sorted(iterable, /, *, key=None, reverse=False)

  • iterable is required.
  • key is optional. It names a function called once per item.
  • reverse is optional. Set it to True for descending order.
  • The return value is always a list.

See the built-in sorted() documentation for the full signature.


Basic sorted() example

python
numbers = [3, 1, 4, 1, 5]
original = numbers.copy()

sorted_numbers = sorted(numbers)

print(sorted_numbers)
print(numbers)
print(numbers is sorted_numbers)
Output

You get a new sorted list, the original list stays unchanged, and the two list objects are different.


sort() vs sorted() in Python

Feature sorted() list.sort()
Type Built-in function List method
Works with Any iterable Lists only
Modifies original No Yes
Return value New list None
Good for Keeping original data Updating an existing list
Syntax sorted(data) data.sort()
Supports key / reverse Yes Yes

The Python tutorial on lists describes list.sort() as an in-place sort. The sorting HOWTO explains that sorted() builds a new sorted list instead.


When to use sorted()

Use sorted() when:

  • You want to keep the original iterable unchanged.
  • You are sorting a tuple, string, set, dictionary, generator, or other non-list iterable.
  • You need a new sorted list for an expression or return value.
  • You are chaining or nesting sorts inside another call.

When to use list.sort()

Use list.sort() when:

  • You already have a list.
  • You want to modify that list in place.
  • You do not need the previous order.
  • You want to avoid creating a second list in memory.
python
scores = [88, 72, 95]
result = scores.sort()

print(scores)
print(result)
Output

After sort(), scores is sorted. result is None, not a sorted list.


sorted() with reverse=True

Use reverse=True for descending order.

python
numbers = [3, 1, 4, 1, 5]

print(sorted(numbers, reverse=True))
Output

For simple numeric descending sorts, reverse=True is clearer than tricks such as key=lambda x: -x.


sorted() with key function

The key argument controls what value is compared for each item. Python calls the key function once per element.

python
words = ["Banana", "apple", "Cherry"]

print(sorted(words))
print(sorted(words, key=str.lower))
print(sorted(words, key=len))
Output

Default sorting is case-sensitive. key=str.lower compares case-insensitively. key=len sorts by string length.

The sorting HOWTO explains how key functions work in detail.


Sort strings with sorted()

sorted("python") returns a list of characters, not a string.

python
text = "python"

print(sorted(text))
print("".join(sorted(text)))
Output

Use "".join(sorted(text)) when you need a sorted string result.


Sort tuple with sorted()

sorted() on a tuple returns a list. Convert back to a tuple only if you need tuple output.

python
data = (4, 1, 3)

sorted_list = sorted(data)
sorted_tuple = tuple(sorted(data))

print(sorted_list)
print(sorted_tuple)
print(type(sorted_list))
Output

For more on tuples, see Python tuple.


Sort dictionary with sorted()

sorted(my_dict) sorts dictionary keys. It does not sort values.

python
data = {"key3": 2, "key1": 5, "key2": 3}

print(sorted(data))
print(sorted(data.items()))
print(sorted(data.items(), key=lambda item: item[1]))
Output

The first line prints sorted keys. The second prints (key, value) pairs sorted by key. The third sorts pairs by value.

For full walkthroughs, see the dedicated dictionary sorting articles linked at the start of this page.


Sort list of dictionaries

Use a key function to sort by one field.

python
from operator import itemgetter

users = [
    {"name": "Bob", "age": 30},
    {"name": "Ann", "age": 30},
    {"name": "Cal", "age": 25},
]

by_age = sorted(users, key=lambda user: user["age"])
by_name = sorted(users, key=itemgetter("name"))

print(by_age[0]["name"])
print(by_name[0]["name"])
Output

The first sort returns Cal because age 25 comes first. The second returns Ann when sorting by name.


Sort list of lists

Sort rows by a column with key=lambda row: row[index].

python
rows = [[2, 34], [1, 43], [3, 56]]

print(sorted(rows, key=lambda row: row[1]))
Output

The rows are ordered by the second column: 34, then 43, then 56.


Stable sorting in Python

Python sorting is stable. Items with equal sort keys keep their original relative order.

python
data = [("a", 1), ("b", 2), ("c", 1)]

print(sorted(data, key=lambda item: item[1]))
Output

Both ("a", 1) and ("c", 1) have key 1, and "a" stays before "c" because it appeared first in the original list.


Sort by multiple criteria

Return a tuple from the key function to sort by more than one field.

python
users = [
    {"age": 30, "name": "Bob"},
    {"age": 30, "name": "Ann"},
    {"age": 25, "name": "Cal"},
]

print(sorted(users, key=lambda user: (user["age"], user["name"])))
Output

Python compares age first, then name when ages tie. Cal comes first, then Ann, then Bob.


Summary

sorted() returns a new sorted list from any iterable. list.sort() modifies a list in place and returns None. Use reverse=True for descending order and key= for custom sorting. Tuple keys handle multiple criteria.


References


Frequently Asked Questions

1. What does sorted() do in Python?

sorted() takes any iterable and returns a new list with the items in ascending order by default. It does not modify the original iterable.

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

sorted() works on any iterable and returns a new list. list.sort() works only on lists, modifies the list in place, and returns None.

3. Does sorted() modify the original list?

No. sorted() always returns a new list. The original list, tuple, string, or other iterable stays unchanged.

4. What does list.sort() return?

list.sort() returns None. Do not write result = my_list.sort() when you expect a sorted list. Use sorted(my_list) instead.

5. What does the key parameter do in sorted()?

key accepts a function that is called once per item. sorted() compares the return values of that function instead of the raw items.

6. Does sorted() always return a list?

Yes. Even when you sort a tuple, string, set, or dictionary, sorted() returns a list.
Deepak Prasad

R&D Engineer

Founder of GoLinuxCloud with more than 15 years of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive …