1
votes

I am working through a preparatory course for a Data Science bootcamp and it goes over the Lambda keyword, 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?

1

1 Answers

3
votes

Personally, a map of a lambda makes me gag. Just use a generator expression! 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.

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 actually preferable for performance reasons, though a generator performs just as well.


BTW, minor correction: lambda is a keyword, not a function.