Python lambda doesn’t support loops. The syntax of it says it supports arguments and expression. Below are the examples that describe the fact that why we can’t use Loops.
Here’s syntax for lambda function
Let us check the syntax, the first part of the syntax is an argument, and the second part is expression.
lambda arguments: expression
The keyword lambda is a must to work this function. It follows arguments and expression.
Simple lambda function
Below function receives two arguments. The first one is ‘3’ and the second one is ‘7’.
def mul1(a1): return lambda b1:b1*a1 myresult = mul1(3) print(myresult(7))
The output is 21.
21 ** Process exited - Return Code: 0 ** Press Enter to exit terminal
Complex lambda function
It prints a range of values. Then for a key to get it sorted, I have used the lambda function.
my_list = range(-3,3) print(my_list) my_list = sorted(my_list, key=lambda x: x*x) print(my_list)
The range values [-3, -2, -1, 0, 1, 2] sorted based on the key. You can see the output and how it’s sorted.
range(-3, 3) [0, -1, 1, -2, 2, -3] ** Process exited - Return Code: 0 ** Press Enter to exit terminal
How to use for loop with lambda
Here’s an example that tells how to use for-loop along with lambda function in python.
def my_add(y): return lambda: y list = [my_add(i) for i in range(1,11)] for z in list: print(z())