1

I am trying to generate a scatter plot with x in range (0,17) and y = 1/(x**2+1). Here's the code that I use to generate the lambda function for y:

y = [lambda x:1/(x**2+1) for x in range(17)]
y

Apparently it shows this output 17 times:

<function __main__.<listcomp>.<lambda>(x)>,
 <function __main__.<listcomp>.<lambda>(x)>,
 <function __main__.<listcomp>.<lambda>(x)>,
 <function __main__.<listcomp>.<lambda>(x)>,

What did I do wrong with the code above? Thanks!

0

2 Answers 2

5

You're not calling the function in the loop.

You can either do

f = lambda x: 1 / (x ** 2 + 1)
y = [f(x) for x in range(17)]

or forgo the lambda and just

y = [1 / (x ** 2 + 1) for x in range(17)]
Sign up to request clarification or add additional context in comments.

3 Comments

You can also map: f = lambda x: 1 / (x ** 2 + 1); y = map(f, range(17))
@Federico You have to call list function again to the map object in order to get the list.
Thanks AKX for your answer!
1

If you indeed wanted to use lambda inside list comp, you should have done this:

>>> y = [(lambda x:1/(x**2+1))(x) for x in range(17)]
>>> y
[1.0, 0.5, 0.2, 0.1, 0.058823529411764705, 0.038461538461538464, 0.02702702702702703, 0.02, 0.015384615384615385, 0.012195121951219513, 0.009900990099009901, 0.00819672131147541, 0.006896551724137931, 0.0058823529411764705, 0.005076142131979695, 0.004424778761061947, 0.0038910505836575876]

Here the x with the lambda has nothing to do with the x being iterated, it is the parameter of the lambda function. The x in the function call outside the parentheses that encloses lambda is the value you are passing to the function.

This was just for explanation purposes, it does not make any sense to write programs this way, the accepted answer is the way you should go.

However, if you want to go crazy with lambda, you can watch David Baezley's talk on lambda calculus with python.

1 Comment

Hi @Sayandip, thanks for the explanation! Indeed, I am new to lambda functions and am having some problems setting them up, and apparently when I should use them. :( I will go and have a watch on the talk. Thanks again!

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.