Help me understand Lambda functions, I checked a lot of codes but I still can't manage to understand it. Maybe with a simple example, thanks in advance.
Asked
Active
Viewed 417 times
-2
-
https://www.google.com/search?sourceid=chrome-psyapi2&ion=1&espv=2&ie=UTF-8&q=python%20lambda%20function&oq=python%20lambda%20function&aqs=chrome..69i57j0l5.3537j0j7 – David Zemens Nov 06 '16 at 16:58
-
https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions – David Zemens Nov 06 '16 at 16:58
-
http://www.diveintopython.net/power_of_introspection/lambda_functions.html – David Zemens Nov 06 '16 at 16:58
-
Thank you I guess – Simeon Aleksov Nov 06 '16 at 16:59
-
Short version: Lambdas are anonymous functions (they don't have a name like normal functions). Often used to create callbacks or to be passed into other function calls – UnholySheep Nov 06 '16 at 17:01
-
Lambas are pretty straight forward - they are anonymous function objects but limited to a single expression so they can be inlined with other code. Perhaps you can give us an example lambda and tell us what's puzzling you. Is it how they work? Is it how they are used? – tdelaney Nov 06 '16 at 17:07
1 Answers
3
Suppose you want to square in value in a list , foo = [1,2,3,4,5]
for i in range(len(a)):
a[i] = a[i] * a[i]
You could use lambda and write
map(lambda x: x * x, foo)
if you want only elements divisible by 3, then
filter(lambda x: x % 3 == 0, foo)
Basically it save you from writing a for loop or to put it better write it in an efficient way.

John Constantine
- 1,038
- 4
- 15
- 43
-
Oh, I see now, by the way, the part "x:" does it mean something like for loop? – Simeon Aleksov Nov 06 '16 at 17:05
-
@BlueMonday That lambda is exactly equivalent to `def some_function(x): return x * x`. Notice that `x` is a parameter and `x * x` is an expression using that parameter. All that happened here is that the code saved a little space by not defining a separate function. Its useful because it moves the interesting part (`x * x`) nearer to its use (the map). – tdelaney Nov 06 '16 at 17:09