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.
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
list.sort(cmp=None, key=None, reverse=False)
# cmp argument existed in Python 2, removed in 3.0Parameters
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
# 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 2Other 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.
# 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]2. sorted function
sorted() can sort any iterable and returns a new list.
Syntax
sorted(iterable, key=None, reverse=False)Parameters
iterable – the collection to sort. key – function that extracts a comparison key from each element. reverse – if True, sort in descending order.
Examples
# 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]))Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Raymond Ops
Linux ops automation, cloud-native, Kubernetes, SRE, DevOps, Python, Golang and related tech discussions.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
