Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Sorting Lists in Python: Comparing sort() and sorted()

Tech May 9 3

Python supports two primary mechanisms for ordering list elements: the in‑place list.sort method and the built‑in sorted function. While both accept the same keyword parameters—key, reversesorted always returns a new list, whereas sort mutates the original in place and returns None.

Function Signatures

sorted(iterable, /, *, key=None, reverse=False)
list.sort(*, key=None, reverse=False)
  • iterable – any iterable (sorted only).
  • key – a callable that extracts a comparison value from each element.
  • reverseTrue for descending order, False (default) for ascending.

Basic Numeric Ordering

values = [9, 2, 7, 1, 4]

# Create a new sorted list
ordered = sorted(values)        # [1, 2, 4, 7, 9]

# Sort in place
values.sort()                   # values is now [1, 2, 4, 7, 9]

Sorting with a Key Function

The key parameter accepts any callable that receives a single element and returns the value used for comparison.

pairs = [('b', 5), ('d', 1), ('c', 3), ('a', 2)]

# Order by the numeric second element only
result = sorted(pairs, key=lambda item: item[1])
# [('d', 1), ('a', 2), ('c', 3), ('b', 5)]

Multi‑Level Sorting

When a sequence of tuples is passed as the key, Python compares element by element, enabling stible multi‑criteria sorts.

records = [('x', 4), ('a', 2), ('y', 2), ('b', 3)]

# Primary sort by second element, secondary by first
arranged = sorted(records, key=lambda r: (r[1], r[0]))
# [('a', 2), ('y', 2), ('b', 3), ('x', 4)]

Descanding Order with reverse

numbers = [5, 2, 3, 1, 4]
desc_sorted  = sorted(numbers, reverse=True)   # [5, 4, 3, 2, 1]

items = ['c', 'a', 'b']
items.sort(reverse=True)                        # items → ['c', 'b', 'a']

Performance Note

Using the key parameter is generally more efficient than providing a custom comparison function, because each element’s key is computed only once rather than during every pairwise evaluation.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.