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
183: Map, Filter, and Their Alternatives
I was looking through some legacy data from a user registration system earlier today, and the data was a complete disaster. We had a list of usernames that were inconsistent—some had trailing whitespace, some were all caps, and some were mixed. When I need to apply the same transformation to every single item in a list, my brain usually goes to a for loop first.
Cleaning up the mess with loops
usernames = [" alice_99 ", "BOB_THE_BUILDER", " Charlie_Brown ", "davey_jones"]
cleaned_users = []
for name in usernames:
cleaned_users.append(name.strip().lower())
print(cleaned_users)
# Output: ['alice_99', 'bob_the_builder', 'charlie_brown', 'davey_jones']
This works perfectly fine. But it's a bit "noisy," isn't it? I'm initializing an empty list, managing the loop, and manually appending. It feels like I'm describing how to do it rather than what I want. This is where map() comes in.
Trying out map()
The map() function is designed to take a function and an iterable, and apply that function to every item. Let's try to replace that loop:
usernames = [" alice_99 ", "BOB_THE_BUILDER", " Charlie_Brown ", "davey_jones"]
# I'll use a lambda here for the strip and lower combo
cleaned_users = map(lambda name: name.strip().lower(), usernames)
print(cleaned_users)
Wait. If you ran that, you didn't get a list. You got something like <map object at 0x...>. This is a classic Python "gotcha." map() doesn't actually return a list; it returns an iterator. It's lazy. It doesn't do the work until you actually ask for the items. To see the results immediately, I have to wrap it in a list() call:
cleaned_users = list(map(lambda name: name.strip().lower(), usernames))
Sifting through the noise
Now, let's say we have a list of user ages, and we only want to keep the ones who are 18 or older. I could use a loop with an if statement, but there's a dedicated tool for this: filter().
ages = [12, 25, 17, 30, 15, 42]
# The function passed to filter must return True or False
adults = filter(lambda age: age >= 18, ages)
print(list(adults))
# Output: [25, 30, 42]
Similar to map(), filter() is lazy. It returns an iterator. It's efficient for massive datasets because it doesn't load the whole result into memory at once, but for most of our daily scripts, the list() wrapper is necessary if we want to print or index the result.
The "Pythonic" alternative
Here is the truth: while map() and filter() are staples of functional programming, most experienced Python developers actually avoid them. Why? Because List Comprehensions do both jobs more readably. Let's look at the same tasks using comprehensions.
# The 'map' alternative
cleaned_users = [name.strip().lower() for name in usernames]
# The 'filter' alternative
adults = [age for age in ages if age >= 18]
Notice how the logic reads almost like an English sentence? "Give me the name stripped and lowered for every name in usernames." It eliminates the need for lambda and the list() wrapper. In my experience, if you can use a list comprehension, do it. Keep map() and filter() in your toolkit for when you're dealing with very large generators or specific functional patterns, but for general data cleaning, comprehensions are king.
📋 Practical Task
Processing a Transaction Ledger
You have been handed a list of transaction amounts from a payment gateway. Some are positive (deposits) and some are negative (withdrawals). However, the data is messy: some values are strings, and some are floats.
Your Goal: Create a new list called verified_deposits that contains only the deposits (values greater than 0) and ensures every value is converted to a float. Use a list comprehension to achieve this in a single line.
transactions = ["10.50", -20.00, "5.00", -1.25, "100.00", -50.0]
# Your code here:
# verified_deposits = ...
The final result should be: [10.5, 5.0, 100.0]
There are no comments for now.