Fundamentals 8 min read

Custom Sorting in Python

This article introduces various methods to customize sorting in Python, including using sorted() function, list's .sort() method, and custom comparison functions.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Custom Sorting in Python

This article introduces various methods to customize sorting in Python, including using sorted() function, list's .sort() method, and custom comparison functions.

1. Using sorted() function: The sorted() function can sort any iterable and return a new sorted list. You can customize the sorting logic using the key parameter.

1.1 Example: Sorting by string length

def sort_by_length(strings): return sorted(strings, key=len) strings = ["hello", "world", "python", "code"] sorted_strings = sort_by_length(strings) print(sorted_strings) # Output: ["code", "hello", "world", "python"]

1.2 Example: Descending order

def sort_by_length_desc(strings): return sorted(strings, key=len, reverse=True) strings = ["hello", "world", "python", "code"] sorted_strings = sort_by_length_desc(strings) print(sorted_strings) # Output: ["python", "world", "hello", "code"]

2. Using list's .sort() method: This method sorts the list in-place. Use the key parameter for custom sorting.

2.1 Example: Sorting by string length

def sort_by_length_inplace(strings): strings.sort(key=len) strings = ["hello", "world", "python", "code"] sort_by_length_inplace(strings) print(strings) # Output: ["code", "hello", "world", "python"]

2.2 Example: Descending order

def sort_by_length_desc_inplace(strings): strings.sort(key=len, reverse=True) strings = ["hello", "world", "python", "code"] sort_by_length_desc_inplace(strings) print(strings) # Output: ["python", "world", "hello", "code"]

3. Using custom comparison functions: Although Python 3 doesn't support cmp, you can use functools.cmp_to_key.

3.1 Example: Ascending order

from functools import cmp_to_key def compare_strings(s1, s2): if len(s1) < len(s2): return -1 elif len(s1) > len(s2): return 1 else: return 0 def sort_by_length_cmp(strings): return sorted(strings, key=cmp_to_key(compare_strings)) strings = ["hello", "world", "python", "code"] sorted_strings = sort_by_length_cmp(strings) print(sorted_strings) # Output: ["code", "hello", "world", "python"]

3.2 Example: Descending order

from functools import cmp_to_key def compare_strings(s1, s2): if len(s1) < len(s2): return 1 elif len(s1) > len(s2): return -1 else: return 0 def sort_by_length_desc_cmp(strings): return sorted(strings, key=cmp_to_key(compare_strings)) strings = ["hello", "world", "python", "code"] sorted_strings = sort_by_length_desc_cmp(strings) print(sorted_strings) # Output: ["python", "world", "hello", "code"]

4. Example: Combining sorting logic

def sort_strings(strings): return sorted(strings, key=lambda s: (len(s), s)) strings = ["hello", "world", "python", "code", "coding"] sorted_strings = sort_strings(strings) print(sorted_strings) # Output: ["code", "coding", "hello", "world", "python"]

5. Using operator.itemgetter: Sort by object attributes.

import operator class Person: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return f"Person({self.name}, {self.age})" people = [ Person("Alice", 25), Person("Bob", 30), Person("Charlie", 20), Person("David", 35) ] def sort_people_by_age(people): return sorted(people, key=operator.attrgetter("age")) sorted_people = sort_people_by_age(people) print(sorted_people) # Output: [Person(Charlie, 20), Person(Alice, 25), Person(Bob, 30), Person(David, 35)]

6. Using functools.partial: Sort based on a custom key function.

import functools def custom_sort_key(person): return person.age + len(person.name) class Person: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return f"Person({self.name}, {self.age})" people = [ Person("Alice", 25), Person("Bob", 30), Person("Charlie", 20), Person("David", 35) ] def sort_people_custom_key(people): custom_key = functools.partial(custom_sort_key) return sorted(people, key=custom_key) sorted_people = sort_people_custom_key(people) print(sorted_people) # Output: [Person(Charlie, 20), Person(Alice, 25), Person(Bob, 30), Person(David, 35)]

7. Conclusion: This article covers various methods to customize sorting in Python, including using sorted() function, list's .sort() method, custom comparison functions, combining sorting logic, using operator.itemgetter, and functools.partial.

programmingSortingComparison FunctionsCustom SortingKey Functions
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login 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.