Welcome to Day 26 of the #80DaysOfChallenges journey! This beginner task tackles sorting a list of books by page count, treating each book as a tuple and using sorted() with a lambda to target the pages. It's a solid practice for custom sorting, showing how lambdas let you pick sort criteria on the fly, useful for organizing data like inventories or lists. If you're dipping into Python's built-ins or need a refresher on anonymous functions, this "Python sort by lambda" example breaks down a reusable sorter that's quick to adapt for other attributes.
💡 Key Takeaways from Day 26: Book Sorting Function
This challenge crafts a function that takes a list of book tuples and returns them ordered by ascending pages. It's a clear case of key-based sorting: feed in data, define the key, get organized output. We'll explore the basics: function structure for sorting, lambda as a sort key, and looping output for display.
1. Function Design: Sorted Return with Key
The sort_library_by_pages function processes the list and hands back the sorted version. Its signature keeps it simple:
def sort_library_by_pages(library_list):
"""
Return a list of books sorted by their number of pages (ascending).
"""
The core line does the work:
# Use the sorted() function with a key to specify sorting by page count
# key=lambda book: book[1] tells Python to sort each tuple by its 2nd element (page count)
sorted_list = sorted(library_list, key=lambda book: book[1])
return sorted_list
This leaves the original list untouched, as sorted() makes a new one. It's modular, ready for tweaks like descending order (add reverse=True) or sorting by other fields, fitting well in apps handling catalogs or rankings.
2. Lambda Key: Targeting the Page Count
The lambda grabs the second tuple element:
key=lambda book: book[1]
Here, book stands in for each tuple, and [1] pulls the pages. It's concise, no need for a full def, ideal for one-off keys. This tech shines when data's structured, like tuples or dicts, letting you sort by name, date, or whatever without restructuring.
3. Example Usage: Printing the Sorted List
Test it with a sample:
books = [
("The Hitchhiker's Guide", 42),
("Pride and Prejudice", 279),
("Moby Dick", 378),
("1984", 328)
]
sorted_books = sort_library_by_pages(books)
print("--- Sorted book list ---")
for book, pages in sorted_books:
print(f"- {book}: {pages} pages")
This outputs the books from fewest to most pages: Hitchhiker's (42), Pride (279), 1984 (328), Moby (378). The for loop unpacks tuples neatly, making the display readable. It's a quick way to verify, and you could extend it to print more details or handle empty lists.
🎯 Summary and Reflections
This book sorter shows lambda's role in making sorts flexible, turning a list into ordered info with minimal fuss. It stuck with me:
- Key power: Lambda lets sorted() focus exactly where you need.
- Non-destructive: New list means originals stay safe.
- Tuple handling: Great for lightweight data pairs.
Surprising how often this pops up, like sorting files by size or scores by value. For extras, try multi-key sorts with tuples in lambda, like (pages, name).
Advanced Alternatives: Use list.sort() for in-place, or itemgetter from operator: key=operator.itemgetter(1). What's your lambda trick for sorting? Comment it!
🚀 Next Steps and Resources
Day 26 leveled up sorting skills, prepping for data wrangling ahead. In #80DaysOfChallenges? Sorted by name instead? Show your mod!
- Source Code for Challenge #26: scripts/sort_library_by_pages.py
- Main Repository: 80-days-of-challenges
- Daily Updates: Twitter/X (@Shahrouzlogs)
Top comments (0)