Fundamentals 4 min read

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 Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Master Python List Sorting: sort() vs sorted() and Custom Comparisons

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.

x = [4, 6, 2, 1, 7, 9]
x.sort()
print(x)  # [1, 2, 4, 6, 7, 9]

2. Getting a Sorted Copy

To keep the original list unchanged, create a shallow copy with slicing and sort the copy:

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]

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:

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]

Even strings can be sorted, producing a list of characters:

print(sorted('Python'))  # ['P', 'h', 'n', 'o', 't', 'y']

3. Custom Comparison Function

You can define your own comparator and pass it to sort() (Python 2 style):

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]

4. Optional Parameters: key and reverse

The key argument specifies a function that extracts a comparison key from each element:

x = ['mmm', 'mm', 'm', 'mm']
x.sort(key=len)
print(x)  # ['m', 'mm', 'mm', 'mmm']

The reverse flag sorts in descending order when set to True:

y = [3, 2, 8, 0, 1]
y.sort(reverse=True)
print(y)  # [8, 3, 2, 1, 0]

- END -

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.

ListSortingsortedsortcustom comparator
Python Programming Learning Circle
Written by

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.

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.