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
75: Lambda Expressions
You've spent a lot of time using def to create functions. It's the right move 95% of the time. But every now and then, you'll find yourself needing a tiny piece of logic—just one line—to pass into another function. Creating a full-blown named function for something that's only used once feels like overkill. That's where lambda expressions come in.
The struggle of sorting dictionaries
Let's say we're building a simple inventory system for a hobby shop. We have a list of products, and each product is a dictionary. I want to sort these products by their price, from cheapest to most expensive.
products = [
{"name": "Solder Station", "price": 45.00},
{"name": "Multimeter", "price": 22.50},
{"name": "Oscilloscope", "price": 120.00},
{"name": "Breadboard", "price": 5.99}
]
If this were a simple list of numbers, products.sort() would work perfectly. But because these are dictionaries, Python has no idea which key to use for the comparison. It'll throw a TypeError because it doesn't know how to compare one dictionary to another.
The "clunky" way to fix it
The standard way to handle this is to provide a key argument to the sort method. This key expects a function that tells Python: "Hey, when you look at this item, use this specific value for the sorting logic."
I could do it the long way, like this:
def get_price(item):
return item["price"]
products.sort(key=get_price)
This works. But honestly? It's a bit tedious. I've just defined a function named get_price that does exactly one thing and will never be used anywhere else in my entire codebase. It's just cluttering up my namespace.
Slimming it down with a lambda
This is the perfect moment for a lambda. A lambda is basically an anonymous, one-line function. The syntax is lambda arguments: expression. No def, no return statement (the result of the expression is returned automatically), and no name.
I can replace that entire get_price function with a single line:
products.sort(key=lambda item: item["price"])
I'm telling Python: "For every item in the list, just use item["price"] as the sorting criteria." It's cleaner, it's faster to write, and it keeps the logic right where it's being used.
Where I went too far
Now, here's a trap I fell into early in my career. I started thinking, "If I can put logic in a lambda, I can put all my logic in lambdas!" I tried to implement a conditional discount right inside the sort key to sort by "effective price."
I wrote something like this:
# Don't do this. It's a nightmare to read.
products.sort(key=lambda i: i["price"] * 0.9 if i["name"] == "Oscilloscope" else i["price"])
I stopped myself halfway through writing that. While it's syntactically legal, it's a readability disaster. The moment you have to use complex ternary operators or nested logic, you've crossed the line. If a lambda takes more than a few seconds for a teammate to parse, just go back to using a regular def function. Lambdas are for simplicity, not for showing off how much you can cram into one line.
📋 Practical Task
Filtering High-Value Transactions from a Ledger
You are working with a list of financial transactions. Each transaction is a dictionary containing an amount and a category. Your goal is to use the filter() function combined with a lambda expression to create a new list containing only the transactions where the amount is greater than 500.
Starter Code:
transactions = [
{"id": 1, "amount": 120.50, "category": "Office Supplies"},
{"id": 2, "amount": 1200.00, "category": "Hardware"},
{"id": 3, "amount": 45.00, "category": "Software"},
{"id": 4, "amount": 850.00, "category": "Hardware"},
{"id": 5, "amount": 300.00, "category": "Marketing"},
]
# Your code here:
# Use filter() and a lambda to get transactions > 500
# Remember that filter() returns an iterator, so wrap it in list()
high_value_transactions =
print(high_value_transactions)There are no comments for now.