Reputation: 129
i have started learning about lambda functions in python and find them somewhat confusing. are they just shortcuts or are there things you need to program that cannot be accomplished without them ?
Upvotes: 0
Views: 317
Reputation: 7177
Lambdas are single-line, unnamed functions.
They are rarely useful, and ISTR they were almost removed from Python in the transition from Python 2.x to Python 3.x.
They violate Python's design principle "There should be one-- and preferably only one --obvious way to do it."
It's almost always better to use a list comprehension, generator expression, or something from the operator module.
In many languages that have lambdas, lambdas are allowed to be multiline. IMO, this gives rise to the software equivalent of a runon sentence. Fortunately, in Python, lambdas are restricted to a single line.
Upvotes: 0
Reputation: 1685
lambda
is just a way to define a function without having to write a full-fledged def
statement.
It's just a handy shortcut, and is never strictly needed. Don't let the weird Greek name scare you away from lambda
.
For example, here's a function defined with def
:
def multiply_by_three(x):
return 3*x
And here's the lambda version:
lambda x: 3*x
They're very similar. In both, you say the argument (which is x
) and then say what you want to do to that argument.
But the difference is that with def
you have to name the function, whereas with lambda
, you don't have to name it! The lambda
simply gives you the function itself, without necessarily giving it a name. This is why functions created with lambda
are called "anonymous functions."
That said, if you want to name a function created with lambda
, you can still do that! Simply assign it to a name, as below:
multiply_by_three = lambda x: 3*x
And this line above would have the exact same effect as the def
statement.
Upvotes: 1
Reputation: 82
Lambdas are just single-line functions, and you are not required to use them in any Python development project. You can look at them as shortcuts for making functions.
def addBy10(number):
return number + 10
// These two produce the same result.
print(addBy10(5))
print(lambda number: number + 10)
They are also useful if you want to repeat a simple process many times, i.e over a list. Instead of using a for loop with a function, you can for instance use Python's 'map()' method and a lambda.
https://medium.com/better-programming/lambda-map-and-filter-in-python-4935f248593
Upvotes: 0