Fundamentals 6 min read

Master Python’s sort vs sorted: When and How to Use Each Efficiently

This article explains the differences between Python's list.sort method and the built‑in sorted function, covering their syntax, parameters, performance nuances, and practical code examples for ascending, descending, and custom key sorting.

Raymond Ops
Raymond Ops
Raymond Ops
Master Python’s sort vs sorted: When and How to Use Each Efficiently

Overall, sort is a method applied to lists that modifies the original list, while the built‑in function sorted can sort any iterable and returns a new object. list.sort() is slightly faster than sorted(iterable).

1. sort function

list.sort() sorts the list in place; it can accept optional arguments to control the sorting behavior. Lists are mutable, tuples cannot be sorted in place.

Syntax

<code>list.sort(cmp=None, key=None, reverse=False)
# cmp argument existed in Python 2, removed in 3.0</code>

Parameters

cmp – optional custom comparison function (Python 2 only). key – function that extracts a comparison key from each element. reverse – if True, sort in descending order.

reverse=True – descending

reverse=False – ascending (default)

Examples

<code># Ascending
aList = [5, 4, 1, 3, 6, 2]
aList.sort()  # [1, 2, 3, 4, 5, 6]

# Descending
aList = [5, 4, 1, 3, 6, 2]
aList.sort(reverse=True)  # [6, 5, 4, 3, 2, 1]

# Sort by second element
def takeSecond(elem):
    return elem[1]

random = [(2, 2), (3, 4), (4, 1), (1, 3)]
random.sort(key=takeSecond)  # [(4, 1), (2, 2), (1, 3), (3, 4)]

# Sort by length
x = ['a', 'bbb', 'cc']
x.sort(key=len)  # ['a', 'cc', 'bbb']

# Custom comparison (Python 2 only)
def comp(x, y):
    if x < y:
        return 1
    elif x > y:
        return -1
    else:
        return 0

aList = [5, 4, 1, 3, 6, 2]
aList.sort(comp)  # descending in Python 2</code>

Other tips

To keep the original list unchanged, create a copy and sort the copy, or use the sorted() function which returns a new sorted list.

<code># Method 1 – copy then sort
aList = [5, 4, 1, 3, 6, 2]
bList = aList[:]  # deep copy
bList.sort()
# bList is [1, 2, 3, 4, 5, 6]

# Method 2 – use sorted
bList = sorted(aList)  # [1, 2, 3, 4, 5, 6]</code>

2. sorted function

sorted() can sort any iterable and returns a new list.

Syntax

<code>sorted(iterable, key=None, reverse=False)</code>

Parameters

iterable – the collection to sort. key – function that extracts a comparison key from each element. reverse – if True, sort in descending order.

Examples

<code># Simple list
a = [5, 2, 3, 1, 4]
sorted(a)  # [1, 2, 3, 4, 5]

# Dictionary keys
b = {1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}
sorted(b)  # [1, 2, 3, 4, 5]

# Sort dictionary items by key
sorted(b.items(), key=lambda x: x[0])

# Sort dictionary items by value length
sorted(b.items(), key=lambda x: len(x[1]))
</code>
Pythoncode examplesprogramming fundamentalsSortingsortedlist.sort
Raymond Ops
Written by

Raymond Ops

Linux ops automation, cloud-native, Kubernetes, SRE, DevOps, Python, Golang and related tech discussions.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.