API Navigator Logo

How to Sort a List in Python

Author: Newtum

This guide covers the two main ways to sort a list in Python: the `list.sort()` method, which sorts the list in-place, and the `sorted()` function, which returns a new sorted list.

`list.sort()`: In-Place Sorting

The `.sort()` method modifies the list directly and returns `None`. It's efficient if you don't need to keep the original, unsorted list.

numbers = [4, 1, 7, 3, 2]
print(f"Original list: {numbers}")

# Sorts the list in ascending order
numbers.sort()
print(f"Sorted list: {numbers}")

# Sort in descending order
numbers.sort(reverse=True)
print(f"Descending sort: {numbers}")

`sorted()`: Returning a New Sorted List

The built-in `sorted()` function takes any iterable as input and returns a new, sorted list. The original list remains unchanged.

numbers = [4, 1, 7, 3, 2]
print(f"Original list: {numbers}")

# Create a new sorted list
sorted_numbers = sorted(numbers)
print(f"New sorted list: {sorted_numbers}")

# The original list is not modified
print(f"Original list after sorted(): {numbers}")

Sorting with a Custom Key

Both methods accept a `key` argument, which is a function that returns a value to sort by. This is powerful for sorting complex objects.

words = ["apple", "Banana", "cherry", "Date"]

# Sort by length of the string
sorted_by_length = sorted(words, key=len)
print(f"Sorted by length: {sorted_by_length}")

# Sort case-insensitively
sorted_case_insensitive = sorted(words, key=str.lower)
print(f"Sorted case-insensitively: {sorted_case_insensitive}")