๐ 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 :
