Understanding Python's sorted() Function and Its Differences from list.sort()
This article explains how Python's built‑in sorted() function sorts any iterable and returns a new list, contrasts it with the in‑place list.sort() method, and demonstrates usage of key functions, reverse ordering, and multi‑dimensional sorting with code examples.
The sorted() built‑in function can sort any iterable and returns a new list, while the list method list.sort() sorts the list in place and returns None .
Syntax: sorted(iterable, key=None, reverse=False) . iterable is the data to sort, key is an optional function that extracts a comparison key from each element, and reverse toggles descending order.
Examples:
g = [1,4,6,8,9,3,5]
sorted(g) # [1,3,4,5,6,8,9]
sorted((1,4,8,9,3,6), reverse=True) # [9,8,6,4,3,1]
sorted('gafrtp') # ['a','f','g','p','r','t']For multi‑dimensional data, the key argument can receive a lambda that selects a tuple element, e.g.:
l = [('a',1),('b',2),('c',6),('d',4),('e',3)]
sorted(l, key=lambda x: x[0])
# [('a',1),('b',2),('c',6),('d',4),('e',3)]
sorted(l, key=lambda x: x[1], reverse=True)
# [('c',6),('d',4),('e',3),('b',2),('a',1)]The same key and reverse parameters can be used with the list method:
l.sort(key=lambda x: x[1])
print(l) # [('a',1),('b',2),('e',3),('d',4),('c',6)]
l.sort(key=lambda x: x[1], reverse=True)
print(l) # [('c',6),('d',4),('e',3),('b',2),('a',1)]The article also notes that the behavior shown applies to Python 3.5 and later.
Test Development Learning Exchange
Test Development Learning Exchange
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.