How to Sort a List in Python | The School of Code

Settings

Appearance

Choose a typography theme that suits your style

Back to How-to Guides
Python

How to Sort a List in Python

Learn different ways to sort lists in Python using sort(), sorted(), and custom sorting.

PythonSortingLists

Python provides multiple ways to sort lists, both in-place and returning new lists.

Method 1: sort() - In-Place Sorting

Modifies the original list:

numbers = [3, 1, 4, 1, 5, 9, 2, 6]

# Sort ascending (default)
numbers.sort()
print(numbers)  # [1, 1, 2, 3, 4, 5, 6, 9]

# Sort descending
numbers.sort(reverse=True)
print(numbers)  # [9, 6, 5, 4, 3, 2, 1, 1]

Method 2: sorted() - Returns New List

Creates a new sorted list:

numbers = [3, 1, 4, 1, 5, 9, 2, 6]

# Sort ascending
sorted_nums = sorted(numbers)
print(sorted_nums)  # [1, 1, 2, 3, 4, 5, 6, 9]
print(numbers)      # [3, 1, 4, 1, 5, 9, 2, 6] (unchanged)

# Sort descending
sorted_desc = sorted(numbers, reverse=True)

Method 3: Custom Sorting with key

Sort by a custom criterion:

# Sort strings by length
words = ["apple", "pie", "banana", "kiwi"]
sorted_words = sorted(words, key=len)
print(sorted_words)  # ['pie', 'kiwi', 'apple', 'banana']

# Sort case-insensitive
names = ["alice", "Bob", "CHARLIE"]
sorted_names = sorted(names, key=str.lower)
print(sorted_names)  # ['alice', 'Bob', 'CHARLIE']

Method 4: Sorting Objects/Dictionaries

Sort complex data structures:

# List of dictionaries
people = [
    {"name": "Alice", "age": 30},
    {"name": "Bob", "age": 25},
    {"name": "Charlie", "age": 35}
]

# Sort by age
by_age = sorted(people, key=lambda x: x["age"])
print(by_age)

# Sort by name
by_name = sorted(people, key=lambda x: x["name"])

Method 5: Multiple Sort Keys

Sort by multiple criteria:

from operator import itemgetter

students = [
    ("Alice", "A", 15),
    ("Bob", "B", 12),
    ("Charlie", "A", 12)
]

# Sort by grade, then by age
sorted_students = sorted(students, key=itemgetter(1, 2))
print(sorted_students)

# Using lambda
sorted_students = sorted(students, key=lambda x: (x[1], x[2]))

Method 6: Reverse Sort

numbers = [3, 1, 4, 1, 5]

# Using reverse parameter
desc = sorted(numbers, reverse=True)

# Or reverse a sorted list
desc = sorted(numbers)[::-1]

Summary

  • Use sort() to modify the original list
  • Use sorted() to get a new sorted list
  • Use key parameter for custom sorting logic
  • Use reverse=True for descending order