0
Lambda confusion
I am struggling with lambda.I don't know how to use lambda🤨Can anyone help me with examples?
4 Respuestas
+ 4
Nvm, I searched your page and noticed you're studying python.
Here are some information and examples.
https://www.w3schools.com/python/python_lambda.asp
0
What is lambda?
0
Lambda is an expression, that returns a function.
lambdas:
-Can only have 1 line of statements, that should end up in 1 single object.
-Do not necessarily need to be given a name in declaration.
-Can be called straight after declaration.
Declaring function with def:
def a(x):
print(x)
Declaring the same function with lambda:
a = lambda x: print(x)
Calling a lambda function straight after declaration without giving it a name:
(lambda: print("Hello"))()
print((lambda x: x + x * 8)(7)) #7 + 7 * 8 = 63
You can use as complex calculations as you want in lambda functions, but it must end up in 1 single object, which means that you can only use statements, that return a value.
For example basic if statement does not return a value, you can not do: x = (if y: print(z)), because if statement self does not return any values.
- 1
If we want to perform an operation squaring the numbers like n*n we have to define a function def and have to create a name. For example,
def square(n):
result n*n
result = square(7)
print(result)
Output = 49.
Here in python we can also create a function without using name . For example,
lambda n : n * n
We know functions in python are objects. So,
f = lambda n : n * n
result = f(7)
print(result)
Output : 49
Hope you understand :)