Python Sort a List – Ascending, Descending, Custom Key
Introduction – Why Learn List Sorting?
Sorting is a fundamental operation in Python programming. Whether you need to sort:
- Numbers
- 🅰️ Strings
- Tuples or objects
- Custom conditions
Python provides powerful and flexible sorting tools using .sort() and sorted().
In this guide, you’ll learn:
- How to sort a list in Python (ascending and descending)
- Difference between
sort()andsorted() - Sort strings, tuples, dictionaries, and objects
- Use custom
keyfunctions for advanced sorting - Best practices for clean, reliable code
1. Sort a List of Numbers – Ascending
nums = [5, 2, 9, 1]
nums.sort()
print(nums) # [1, 2, 5, 9]
list.sort() sorts the list in place.
2. Sort a List of Numbers – Descending
nums = [5, 2, 9, 1]
nums.sort(reverse=True)
print(nums) # [9, 5, 2, 1]
Add reverse=True to flip the order.
3. Use sorted() – Returns a New List
nums = [5, 2, 9, 1]
new_nums = sorted(nums)
print(new_nums) # [1, 2, 5, 9]
print(nums) # Original remains unchanged
Use sorted() when you don’t want to modify the original list.
4. Sort Strings Alphabetically
words = ["banana", "apple", "cherry"]
words.sort()
print(words) # ['apple', 'banana', 'cherry']
Case-Insensitive Sort
words = ["Banana", "apple", "Cherry"]
words.sort(key=str.lower)
print(words) # ['apple', 'Banana', 'Cherry']
Use key=str.lower to ignore case sensitivity.
5. Sort by Length of Words
words = ["a", "apple", "banana"]
words.sort(key=len)
print(words) # ['a', 'apple', 'banana']
Pass any function to key for custom sort criteria.
6. Sort a List of Tuples by Second Value
items = [(1, 'b'), (3, 'a'), (2, 'c')]
items.sort(key=lambda x: x[1])
print(items) # [(3, 'a'), (1, 'b'), (2, 'c')]
Use lambda functions for advanced sorting logic.
7. Sort List of Dictionaries by a Key
people = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]
people.sort(key=lambda x: x["age"])
print(people) # [{'name': 'Bob', ...}, {'name': 'Alice', ...}]
Sort complex structures like JSON or database records.
8. Sort Custom Objects with attrgetter
from operator import attrgetter
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
people = [Person("Alice", 30), Person("Bob", 25)]
people.sort(key=attrgetter("age"))
for p in people:
print(p.name, p.age)
Cleaner and faster than lambda x: x.attr.
9. Stable Sort – Order is Preserved for Equal Items
data = [(2, 'a'), (1, 'b'), (1, 'c')]
sorted_data = sorted(data, key=lambda x: x[0])
print(sorted_data) # [(1, 'b'), (1, 'c'), (2, 'a')]
Python uses Timsort – a stable sorting algorithm.
Best Practices
| Do This | Avoid This |
|---|---|
Use .sort() to sort in-place | Expecting .sort() to return a new list |
Use sorted() for non-destructive sort | Overwriting original list unnecessarily |
Use key with lambda or functions | Using nested loops for sorting |
Use attrgetter for object attributes | Writing long lambda chains unnecessarily |
Summary – Recap & Next Steps
Python makes sorting intuitive and powerful. You can sort numbers, strings, tuples, dictionaries, and objects with ease using sort() and sorted().
Key Takeaways:
- Use
.sort()for in-place sorting - Use
sorted()to get a new list - Use
keyfunctions to customize sorting - Use
reverse=Truefor descending order - Python’s sort is stable and fast (Timsort)
Real-World Relevance:
Used in data processing, search filters, leaderboards, sorting records, and ranking systems.
FAQ – Python Sort a List
What is the difference between sort() and sorted()?
sort()changes the original listsorted()returns a new sorted list
How do I sort in descending order?
Use reverse=True:
sorted(data, reverse=True)
Can I sort by multiple keys?
Yes, use a tuple in key:
data.sort(key=lambda x: (x[0], x[1]))
Does sorting change the original list?
sort()– Yessorted()– No (non-destructive)
Can I sort a list of dictionaries?
Yes, using key=lambda x: x["field"]
Share Now :
