Master Python List Sorting: sort() vs sorted() and Custom Comparisons
This guide explains Python's list sorting methods, showing how the in‑place sort() works, how to obtain sorted copies with slicing or the sorted() function, and how to use custom comparison functions and optional key and reverse parameters for flexible ordering.
Python's sort() method sorts a list in place, while the sorted() function returns a new sorted list without modifying the original.
1. Basic Usage
Lists have a built‑in sort() method that rearranges the elements directly; tuples cannot use it because they are immutable.
<code>x = [4, 6, 2, 1, 7, 9]
x.sort()
print(x) # [1, 2, 4, 6, 7, 9]
</code>2. Getting a Sorted Copy
To keep the original list unchanged, create a shallow copy with slicing and sort the copy:
<code>x = [4, 6, 2, 1, 7, 9]
y = x[:]
y.sort()
print(y) # [1, 2, 4, 6, 7, 9]
print(x) # [4, 6, 2, 1, 7, 9]
</code>Note: y = x[:] copies the list, whereas y = x would only create another reference to the same list.
Alternatively, use the sorted() function, which works on any iterable and always returns a new list:
<code>x = [4, 6, 2, 1, 7, 9]
y = sorted(x)
print(y) # [1, 2, 4, 6, 7, 9]
print(x) # [4, 6, 2, 1, 7, 9]
</code>Even strings can be sorted, producing a list of characters:
<code>print(sorted('Python')) # ['P', 'h', 'n', 'o', 't', 'y']
</code>3. Custom Comparison Function
You can define your own comparator and pass it to sort() (Python 2 style):
<code>def comp(x, y):
if x < y:
return 1
elif x > y:
return -1
else:
return 0
nums = [3, 2, 8, 0, 1]
nums.sort(comp)
print(nums) # descending order: [8, 3, 2, 1, 0]
</code>4. Optional Parameters: key and reverse
The key argument specifies a function that extracts a comparison key from each element:
<code>x = ['mmm', 'mm', 'm', 'mm']
x.sort(key=len)
print(x) # ['m', 'mm', 'mm', 'mmm']
</code>The reverse flag sorts in descending order when set to True :
<code>y = [3, 2, 8, 0, 1]
y.sort(reverse=True)
print(y) # [8, 3, 2, 1, 0]
</code>- END -
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.