1

Any way to improve the code with a better solution?

say in the list nums = [1, 2, 3, 4, 5, 6], want to use lambda to do a simple calculation for num%2 == 0 only as the following:

print map(lambda n:n**2, filter(lambda n: n%2!=0, nums))

Just wonder if any way to just use one lambda expression for it?

4
  • So you want the get the output: [1, 9, 25]? Commented May 11, 2017 at 16:35
  • 1
    you can use list compression [ num * num for num in nums if num % 2 == 0 ] Commented May 11, 2017 at 16:36
  • 1
    you mean [ num * num for num in nums if num % 2 != 0 ] Commented May 11, 2017 at 16:39
  • 1
    In CPython, it is best to avoid map and filter with non-builtin functions, and you should instead use the equivalent comprehsion construct. Commented May 11, 2017 at 16:41

1 Answer 1

3

If you really want to use lambda, you can do it with one lambda that issues the squared value or 0 depending on the oddness of the input, using a ternary expression (but you still have to filter using None so only non-zero numbers are kept)

nums = [1, 2, 3, 4, 5, 6]
result = list(filter(None,map(lambda n:n**2 if n%2 else 0,nums)))

result:

[1, 9, 25]

note that list conversion is required only for python 3.

Of course, all those filter, map, ... chaining renders the lambda inefficient/not that useful. You'd be better off with a simple list comprehension.

result = [n**2 for n in nums if n%2]

map should be only needed when you have the function (or built-in) handy (like map(str,my_list) for instance). All those chained calls could be less performant than that simple list comprehension in the end.

A more detailed explanation here: https://docs.python.org/2/howto/functional.html#small-functions-and-the-lambda-expression

Which alternative is preferable? That’s a style question; my usual course is to avoid using lambda. One reason for my preference is that lambda is quite limited in the functions it can define. The result has to be computable as a single expression, which means you can’t have multiway if... elif... else comparisons or try... except statements. If you try to do too much in a lambda statement, you’ll end up with an overly complicated expression that’s hard to read.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.