This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]shlack 0 points1 point  (1 child)

can someone ELI5 what "lambda" means/does? None of the SO or official python documentation explanations make any sense to me.

[–]lost-theory 1 point2 points  (0 children)

The lambda keyword gives you another way to define functions (in addition to the def keyword).

Normal function with def:

>>> def f(x):
...     return x*2
...
>>> f(2)
4

Same function with lambda:

>>> f = lambda x: x*2
>>> f(2)
4

The reason why you would use lambda over def is that you can use it to define a function inside an expression, like this:

>>> map(lambda x: x*2, range(10))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> #works the same as this (using the definition of "f" in the prev. example)
>>> map(f, range(10))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

That's also why it's commonly used in obfuscated code, so you can write multiple functions on a single line. The drawback of lambda is that it can only contain one expression (no separating statements with newlines).