Sorting lists is one of the most common operations in Python programming, and knowing how to python sort list efficiently can save you hours of writing manual loops. Python gives you two powerful built-in tools to sort lists: the list.sort() method and the sorted() function. Whether you need to python sort list of strings, numbers, tuples, or custom objects, these tools handle it all. In this guide, you'll learn exactly how to python sort list data in ascending order, descending order, by a custom key, and more — with clear examples for each approach.
list.sort() MethodThe list.sort() method sorts a list in place, meaning it modifies the original list directly and returns None. This is the go-to way to python sort list when you don't need to keep the original order.
fruits = ["banana", "apple", "cherry", "mango"]
fruits.sort()
print(fruits)
# Output: ['apple', 'banana', 'cherry', 'mango']
The list.sort() method sorts elements in ascending order by default. Since it modifies the list in place, the original list is permanently changed after calling it.
Syntax:
list.sort(key=None, reverse=False)
key — an optional function to extract a comparison value from each elementreverse — set to True to python sort descendingsorted() FunctionThe sorted() function works differently from list.sort() — it returns a new sorted list and leaves the original list unchanged. This makes the python sorted() function ideal when you need both the original and sorted versions.
scores = [42, 17, 95, 3, 61]
sorted_scores = sorted(scores)
print(sorted_scores) # [3, 17, 42, 61, 95]
print(scores) # [42, 17, 95, 3, 61] — original unchanged
Syntax:
sorted(iterable, key=None, reverse=False)
Unlike list.sort(), the python sorted() function works on any iterable — lists, tuples, sets, dictionaries, and more. It always returns a list.
By default, both sort() and sorted() perform ascending order sorting. For numbers, smallest comes first. For strings, alphabetical (lexicographic) order is used.
numbers = [100, 5, 83, 22, 47]
numbers.sort()
print(numbers)
# Output: [5, 22, 47, 83, 100]
Ascending order is the default behavior, so you don't need to pass any arguments for this case.
To python sort descending, pass reverse=True to either sort() or sorted().
temperatures = [72, 88, 65, 95, 79]
temperatures.sort(reverse=True)
print(temperatures)
# Output: [95, 88, 79, 72, 65]
Using sorted() for descending order:
grades = [85, 92, 78, 96, 60]
desc_grades = sorted(grades, reverse=True)
print(desc_grades)
# Output: [96, 92, 85, 78, 60]
The reverse=True parameter works identically in both sort() and sorted(), and it applies after the key function is evaluated (if any).
Sorting a python sort list of strings uses alphabetical (lexicographic) ordering by default. Uppercase letters are sorted before lowercase letters because Python uses Unicode code points for comparison.
cities = ["Tokyo", "berlin", "Paris", "amsterdam", "London"]
cities.sort()
print(cities)
# Output: ['London', 'Paris', 'Tokyo', 'amsterdam', 'berlin']
Notice that uppercase letters come before lowercase. To do a case-insensitive python sort list of strings, use str.lower as the key:
cities = ["Tokyo", "berlin", "Paris", "amsterdam", "London"]
cities.sort(key=str.lower)
print(cities)
# Output: ['amsterdam', 'berlin', 'London', 'Paris', 'Tokyo']
The key=str.lower tells Python to compare the lowercase version of each string, without actually changing the strings in the list.
The key parameter is the most powerful feature of the python sort list tools. It accepts any callable (a function, lambda, or method) and applies it to each element before comparison. The original elements are kept — only the comparison uses the key's result.
Sorting strings by length:
words = ["elephant", "cat", "hippopotamus", "dog", "bird"]
words.sort(key=len)
print(words)
# Output: ['cat', 'dog', 'bird', 'elephant', 'hippopotamus']
Sorting with a lambda function:
products = ["apple_3", "banana_1", "cherry_2"]
products.sort(key=lambda x: x.split("_")[1])
print(products)
# Output: ['banana_1', 'cherry_2', 'apple_3']
Sorting dictionaries by a specific field:
employees = [
{"name": "Alice", "salary": 72000},
{"name": "Bob", "salary": 95000},
{"name": "Carol", "salary": 58000},
]
employees.sort(key=lambda emp: emp["salary"])
for e in employees:
print(e["name"], e["salary"])
# Output:
# Carol 58000
# Alice 72000
# Bob 95000
The key function is called exactly once per element, so even complex operations don't slow things down unnecessarily. Python's sort uses the Timsort algorithm, which is highly optimized for real-world data.
A python sort list of tuples is sorted element-by-element by default — first by index 0, then by index 1 if index 0 values are equal, and so on. This is called lexicographic tuple comparison.
coordinates = [(3, 7), (1, 5), (3, 2), (1, 9), (2, 4)]
coordinates.sort()
print(coordinates)
# Output: [(1, 5), (1, 9), (2, 4), (3, 2), (3, 7)]
Sort a python sort list of tuples by the second element:
student_scores = [("Alice", 88), ("Bob", 72), ("Carol", 95), ("Dave", 72)]
student_scores.sort(key=lambda t: t[1])
print(student_scores)
# Output: [('Bob', 72), ('Dave', 72), ('Carol', 95) ...] # unstable? No — Timsort is stable!
# Actual Output: [('Bob', 72), ('Dave', 72), ('Alice', 88), ('Carol', 95)]
Python's sort is stable, meaning elements with equal keys retain their original relative order. So Bob appears before Dave since both scored 72 and Bob came first.
Sort by multiple fields — first by score descending, then by name ascending:
student_scores = [("Alice", 88), ("Bob", 72), ("Carol", 95), ("Dave", 72)]
student_scores.sort(key=lambda t: (-t[1], t[0]))
print(student_scores)
# Output: [('Carol', 95), ('Alice', 88), ('Bob', 72), ('Dave', 72)]
The trick (-t[1], t[0]) sorts score in descending order (by negating it) and name in ascending order.
sort() vs sorted() — Key DifferencesUnderstanding when to use each is important for clean, efficient code.
| Feature | list.sort() | sorted() |
|---|---|---|
| Modifies original list | ✅ Yes (in place) | ❌ No |
| Returns value | None | New sorted list |
| Works on any iterable | ❌ Lists only | ✅ Any iterable |
| Memory usage | Lower (in place) | Higher (new list) |
Use list.sort() when you want to save memory and don't need the original order. Use sorted() when you need to keep the original list intact or you're working with a non-list iterable.
Here's a complete Python program that demonstrates all the key ways to python sort list data, including ascending, descending, python sort list of strings, python sort list of tuples, and python sort by key.
# Python Sort List — Full Working Example
# --- 1. Sort list of numbers ascending (list.sort)
numbers = [64, 12, 99, 33, 7, 51]
numbers.sort()
print("Ascending:", numbers)
# Output: Ascending: [7, 12, 33, 51, 64, 99]
# --- 2. Sort list of numbers descending (sorted)
numbers2 = [64, 12, 99, 33, 7, 51]
desc = sorted(numbers2, reverse=True)
print("Descending:", desc)
# Output: Descending: [99, 64, 51, 33, 12, 7]
# --- 3. Python sort list of strings (case-insensitive)
languages = ["Ruby", "python", "JavaScript", "go", "TypeScript"]
languages.sort(key=str.lower)
print("Languages (case-insensitive):", languages)
# Output: Languages (case-insensitive): ['go', 'JavaScript', 'python', 'Ruby', 'TypeScript']
# --- 4. Python sort by key — sort by string length
animals = ["rhinoceros", "ox", "flamingo", "ant", "zebra"]
by_length = sorted(animals, key=len)
print("By length:", by_length)
# Output: By length: ['ox', 'ant', 'zebra', 'flamingo', 'rhinoceros']
# --- 5. Python sort list of tuples by second element
inventory = [("apples", 50), ("bananas", 20), ("cherries", 80), ("dates", 35)]
inventory.sort(key=lambda item: item[1])
print("Inventory by quantity:")
for name, qty in inventory:
print(f" {name}: {qty}")
# Output:
# bananas: 20
# dates: 35
# apples: 50
# cherries: 80
# --- 6. Sort list of dicts by key (descending)
students = [
{"name": "Jordan", "gpa": 3.5},
{"name": "Taylor", "gpa": 3.9},
{"name": "Morgan", "gpa": 3.2},
{"name": "Riley", "gpa": 3.9},
]
students.sort(key=lambda s: (-s["gpa"], s["name"]))
print("\nStudents by GPA (desc), name (asc):")
for s in students:
print(f" {s['name']}: {s['gpa']}")
# Output:
# Riley: 3.9
# Taylor: 3.9
# Jordan: 3.5
# Morgan: 3.2
Expected Output:
Ascending: [7, 12, 33, 51, 64, 99]
Descending: [99, 64, 51, 33, 12, 7]
Languages (case-insensitive): ['go', 'JavaScript', 'python', 'Ruby', 'TypeScript']
By length: ['ox', 'ant', 'zebra', 'flamingo', 'rhinoceros']
Inventory by quantity:
bananas: 20
dates: 35
apples: 50
cherries: 80
Students by GPA (desc), name (asc):
Riley: 3.9
Taylor: 3.9
Jordan: 3.5
Morgan: 3.2
For deeper reading on Python's sorting capabilities, check the official Python Sorting HOW TO and the sorted() built-in documentation.
Ready to go deeper? This guide is part of a complete Python tutorial series covering everything from basics to advanced topics. Whether you're just starting out or looking to sharpen your skills, the full series has you covered. Learn the full Python tutorial here.