Skip to Content
Course content

183: Map, Filter, and Their Alternatives

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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]

Rating
0 0

There are no comments for now.

to be the first to leave a comment.