Last modified: Oct 28, 2024 By Alexander Williams

Python Sort List: A Complete Guide

Sorting lists in Python is essential for organizing data. Python provides multiple methods to sort lists quickly and efficiently.

Basic Sorting with sort()

The sort() method sorts a list in-place in ascending order by default. This method changes the original list.


numbers = [4, 2, 9, 1]
numbers.sort()

After sorting, numbers becomes [1, 2, 4, 9]. Note that sort() does not return a new list.

Sorting in Descending Order

To sort a list in descending order, set the reverse parameter of sort() to True.


numbers.sort(reverse=True)

This will reorder numbers to [9, 4, 2, 1].

Sorting with sorted()

sorted() returns a new sorted list, leaving the original list unchanged. It is ideal when you need a temporary sort.


sorted_numbers = sorted(numbers)

Here, sorted_numbers is a sorted copy, while numbers remains the same.

Custom Sorting with key Parameter

You can define custom sort criteria using the key parameter, which accepts a function to customize the sort order.


words = ["banana", "apple", "kiwi"]
words.sort(key=len)

This sorts words based on length, resulting in ["kiwi", "apple", "banana"].

Sorting a List of Lists

To sort a list of lists by elements within each sublist, use key with lambda for custom sorting.


pairs = [[1, 3], [2, 2], [4, 1]]
pairs.sort(key=lambda x: x[1])

This sorts pairs by the second element in each sublist, resulting in [[4, 1], [2, 2], [1, 3]].

Sorting Lists of Strings

String lists are sorted alphabetically by default. sort() and sorted() both work with strings.


fruits = ["orange", "apple", "banana"]
fruits.sort()

This changes fruits to ["apple", "banana", "orange"]. For more on lists, see Creating Lists in Python: A Beginner's Guide.

Conclusion

Python’s sorting functions offer flexibility for organizing data, allowing sorting by order, data type, or custom conditions.

For a detailed overview, check the official Python sorting documentation for more techniques and examples.