0

In generating a list as below, the lambda function is declared outside the squared brackets, then applied for each i,

>>> g = lambda x: x*10
>>> [g(i) for i in range(10,21)]
[100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200]

Is it possible (and how) to declare the lambda function within the list and call it ?

5
  • 2
    First guess: [(lambda x: x*10)(i) for i in range(10,21)]. Why do you feel you want to do this? Commented Jan 9, 2015 at 20:26
  • 1
    You'll end up producing slow and unreadable code Commented Jan 9, 2015 at 20:28
  • @enzyme Be careful, short code does not always mean efficient code in Python. Commented Jan 9, 2015 at 20:34
  • you would never ever want to do this. a lambda is just a one-line function and you can easily just put its body inside the list comprehension. Commented Jan 9, 2015 at 20:36
  • Assigning a lambda to a variable is rarely correct but a bunch of horrible lambda tutorials do it anyway. Commented Jan 9, 2015 at 21:00

2 Answers 2

5

The insane way:

[(lambda x: x*10)(i) for i in range(10,21)]

The sane way:

[i * 10 for i in range(10,21)]
Sign up to request clarification or add additional context in comments.

1 Comment

Explanation: The problem with declaring the lambda function in the comprehension is that the function will be repeatedly created for each item in the list. Since the body of a lambda is a single expression, it is better to put that expression directly into the comprehension.
3

you can use map too:

>>> list(map(lambda x:x*10,range(10,21)))
[100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200]

4 Comments

Great answer except that map returns a list so doesn't need to be converted.
oops, should have thought about that. the comment is true for python 2.
Grt by urself you realize it :)
@tdelaney Python 2 version: map(lambda x:x*10, xrange(10,21)).

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.