Fundamentals 7 min read

Master Python list.sort vs sorted: Tips, Syntax, and Real-World Examples

This guide explains the differences between Python's list.sort method and the sorted function, covering their syntax, parameters, performance nuances, and practical examples such as ascending/descending order, custom key functions, and creating sorted copies without altering the original list.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python list.sort vs sorted: Tips, Syntax, and Real-World Examples

Overall, sort modifies the original list, while sorted returns a new sorted object. list.sort() is slightly faster than sorted(iter).

1. The sort() Method

sort() sorts the list in place; it can accept optional parameters to define the sorting behavior. Only mutable sequences like lists can be sorted, not tuples.

Syntax

list.sort(cmp=None, key=None, reverse=False)
# cmp parameter existed in Python 2.0
# removed in Python 3.0

Parameters

cmp – optional custom comparison function (Python 2 only) key – function that extracts a comparison key from each element reverse – sort order (True for descending, False for ascending, default)

reverse=True – descending

reverse=False – ascending (default)

The method sorts the original list in place and returns None.

Examples

# 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)
aList  # [6, 5, 4, 3, 2, 1]

# Sort by a specific element (second element of tuple)
def takeSecond(elem):
    return elem[1]

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

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

# Custom comparison function (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 order (Python 2)

Other Tips

To obtain a sorted copy while keeping the original list unchanged, use either slicing with sorted or the list.copy() method.

# Method 1: copy then sort
aList = [5, 4, 1, 3, 6, 2]
bList = aList[:]  # deep copy
bList.sort()
print(aList)  # [5, 4, 1, 3, 6, 2]
print(bList)  # [1, 2, 3, 4, 5, 6]

# Method 2: use sorted
aList = [5, 4, 1, 3, 6, 2]
bList = sorted(aList)  # [1, 2, 3, 4, 5, 6]

Copying via slicing creates a new list; simple assignment would reference the same list.

2. The sorted() Function

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

Syntax

sorted(iterable, key=None, reverse=False)

Parameters

iterable – the collection to sort key – function to extract a comparison key from each element reverse – sort order (True for descending, False for ascending)

The function returns a new list containing the sorted items.

Examples

# Default ascending sort
a = [5, 2, 3, 1, 4]
sorted(a)  # [1, 2, 3, 4, 5]

# Sorting a dictionary's 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]))

Other Example

# Medal ranking example
s = "Germany 10 11 16
Italy 10 10 20
Netherlands 10 12 14
France 10 12 11
UK 22 21 22
China 38 32 18
Japan 27 14 17
USA 39 41 33
ROC 20 28 23
Australia 17 7 22
Hungary 6 7 7
Canada 7 6 11
Cuba 7 3 5
Brazil 7 6 8
New Zealand 7 6 7"
stodata = s.split('
', -1)
para = {}
for line in range(len(stodata)):
    data = stodata[line].split(' ')
    print(data)
    para[data[0]] = [int(i) for i in data[1:]]

new_para = sorted(para.items(), key=lambda x: (x[1], x[0]))
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonData StructuresCode ExamplesSortingsortedlist.sort
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

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.