Understanding Python's list.sort() Method and sorted() Function
This article explains how Python's list.sort() method sorts a list in place, how the built‑in sorted() function returns a new sorted list for any iterable, and demonstrates various parameters, custom key functions, and practical code examples for effective sorting.
Python provides two primary ways to sort collections: the list method list.sort() , which sorts the list in place, and the built‑in function sorted() , which returns a new sorted list from any iterable.
list.sort() Function
The list.sort() method modifies the original list and accepts optional cmp (removed in Python 3), key , and reverse parameters. It returns None because the sorting is performed in place.
<code>list.sort(cmp=None, key=None, reverse=False)
# cmp parameter existed in Python 2.0
# removed in Python 3.0</code>Common parameters:
key : a function that extracts a comparison key from each element.
reverse : True for descending order, False (default) for ascending.
Examples
<code># Ascending order
aList = [5, 4, 1, 3, 6, 2]
aList.sort() # [1, 2, 3, 4, 5, 6]
# Descending order
aList = [5, 4, 1, 3, 6, 2]
aList.sort(reverse=True)
# aList => [6, 5, 4, 3, 2, 1]
# Sort by a specific element (e.g., second element of a 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 of strings
x = ['a', 'bbb', 'cc']
x.sort(key=len)
# x => ['a', 'cc', 'bbb']
# Custom compare 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) # works in Python 2 for descending order</code>Other Tips
To keep the original list unchanged, create a copy before sorting or use the sorted() function.
<code># 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)
# bList => [1, 2, 3, 4, 5, 6]
</code>sorted() Function
The built‑in sorted() function works on any iterable, returns a new list, and accepts the same key and reverse arguments.
<code>sorted(iterable, key=None, reverse=False)</code>Parameters:
iterable : the collection to be sorted.
key : a function to extract a comparison key.
reverse : True for descending order.
Examples
<code># Simple list sorting
a = [5, 2, 3, 1, 4]
sorted(a) # [1, 2, 3, 4, 5]
# Sorting dictionary keys
b = {1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}
sorted(b) # [1, 2, 3, 4, 5]
# Sorting dictionary items by key
sorted(b.items(), key=lambda x: x[0])
# Sorting dictionary items by value length
sorted(b.items(), key=lambda x: len(x[1]))
</code>Other Use Cases
Complex data can be sorted by multiple criteria, as shown in the medal‑ranking example where country data is parsed and sorted by medal counts.
<code>s = "Germany 10 11 16\nItaly 10 10 20\n..."
stodata = s.split('\n', -1)
para = {}
for line in range(len(stodata)):
data = stodata[line].split(' ')
para[data[0]] = [int(i) for i in data[1:]]
new_para = sorted(para.items(), key=lambda x: (x[1], x[0]))
</code>These examples illustrate how to choose between in‑place sorting with list.sort() and creating a new sorted list with sorted() , depending on whether the original data should be preserved.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
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.