When and why to map a lambda function to a list

Question:

I am working through a preparatory course for a Data Science bootcamp and it goes over the lambda keyword and map and filter functions fairly early on in the course. It gives you syntax and how to use it, but I am looking for why and when for context. Here is a sample of their solutions:

def error_line_traces(x_values, y_values, m, b):
    return list(map(lambda x_value: error_line_trace(x_values, y_values, m, b, x_value), x_values))

I feel as if every time I go over their solutions to the labs I’ve turned a single return line solution into a multi-part function. Is this style or is it something that I should be doing?

Asked By: EmperorNero

||

Answers:

I’m not aware of any situations where it makes sense to use a map of a lambda, since it’s shorter and clearer to use a generator expression instead. And a list of a map of a lambda is even worse cause it could be a list comprehension:

def error_line_traces(x_values, y_values, m, b):
    return [error_line_trace(x_values, y_values, m, b, x) for x in x_values]

Look how much shorter and clearer that is!

A filter of a lambda can also be rewritten as a comprehension. For example:

list(filter(lambda x: x>5, range(10)))
[x for x in range(10) if x>5]

That said, there are good uses for lambda, map, and filter, but usually not in combination. Even list(map(...)) can be OK depending on the context, for example converting a list of strings to a list of integers:

[int(x) for x in list_of_strings]
list(map(int, list_of_strings))

These are about as clear and concise, so really the only thing to consider is whether people reading your code will be familiar with map, and whether you want to give a meaningful name to the elements of the iterable (here x, which, admittedly, is not a great example).

Once you get past the bootcamp, keep in mind that map and filter are iterators and do lazy evaluation, so if you’re only looping over them and not building a list, they’re often preferable for performance reasons, though a generator will probably perform just as well.

Answered By: wjandrea
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.