Python
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
35: Sorting Lists with sort() and sorted()
Imagine you have a stack of printed invoices sitting on your desk. You realize they're in a random jumble, and you need them in date order. You have two ways to handle this. First, you could physically slide the papers around on your desk until the original stack is organized. Now, the original pile is sorted, but the previous "random" order is gone forever. Or, you could take that stack to the photocopier, make a copy of every page, and organize those copies into a new pile. In the second scenario, you have a sorted list, but your original, messy stack is still sitting exactly where you left it.
In Python, this is exactly the difference between .sort() and sorted(). One changes the original list (the desk), and the other gives you a brand new one (the photocopy).
Changing the Original with .sort()
When you call the .sort() method on a list, you're telling Python to rearrange the items inside that specific list. It's called "in-place" sorting. I usually use this when I don't care about the original order and want to save a bit of memory by not creating a second list.
# Let's say we have a list of usernames
users = ["zara", "alex", "morgan", "ben"]
users.sort()
print(users)
# Output: ['alex', 'ben', 'morgan', 'zara']
One thing that trips up a lot of people: .sort() returns None. If you try to write my_list = users.sort(), you'll accidentally wipe out your list and replace it with None. Don't do that. Just call the method on its own line.
Creating a Copy with sorted()
If you need to keep the original data exactly as it was—maybe for an audit trail or because another part of your program expects the original sequence—use the sorted() function. This doesn't touch the original list; it just hands you back a new, sorted version of it.
original_scores = [42, 7, 99, 12]
ranked_scores = sorted(original_scores)
print(original_scores) # [42, 7, 99, 12] - Still messy!
print(ranked_scores) # [7, 12, 42, 99] - All clean.
Flipping the Order and Custom Logic
By default, Python sorts everything in ascending order (A-Z or smallest to largest). If you want the opposite, you don't need to sort and then reverse the list in two steps. Both .sort() and sorted() accept a reverse=True argument.
But the real power comes from the key parameter. This lets you tell Python, "Don't sort based on the item itself; sort based on this specific characteristic of the item." For example, if you want to sort a list of names by the length of the name rather than alphabetically, you pass the len function as the key.
names = ["Christopher", "Amy", "Joe", "Alexandra"]
# Sort by the length of the string
names.sort(key=len)
print(names)
# Output: ['Amy', 'Joe', 'Alexandra', 'Christopher']
I find the key parameter incredibly useful when dealing with complex data, like lists of dictionaries or tuples, where you only want to sort by one specific field.
📋 Practical Task
The High-Score Leaderboard Organizer
You are building a gaming leaderboard. You have a list of players and their scores stored as tuples: ("PlayerName", score). Your goal is to display the leaderboard from the highest score to the lowest score.
Requirements:
- Start with this list:
players = [("Alice", 1200), ("Bob", 4500), ("Charlie", 3200), ("Diana", 4500)] - Create a new list called
leaderboardthat is sorted by the score (the second element of the tuple) in descending order. - Ensure the original
playerslist remains unchanged. - Use a
lambdafunction as thekeyto target the score index.
# Your code here:
players = [("Alice", 1200), ("Bob", 4500), ("Charlie", 3200), ("Diana", 4500)]
# Create the sorted leaderboard list below
There are no comments for now.