lambda with default arguments in python

We can use lambda functions in Python with default arguments using the same syntax as regular functions. Here's an example:

main.py
my_lambda = lambda x, y=5: x + y
33 chars
2 lines

In the code above, we have a lambda function that takes two arguments x and y with a default value of 5. The lambda function simply returns the sum of x and y.

We can now call my_lambda and pass in one or two arguments:

main.py
result1 = my_lambda(3)      # returns 8 (3 + 5)
result2 = my_lambda(3, 7)   # returns 10 (3 + 7)
97 chars
3 lines

In the first call, we only passed in one argument (3), so y defaults to 5 and the result is 8. In the second call, we passed in two arguments (3 and 7), so y is set to 7 and the result is 10.

gistlibby LogSnag