w3resource

Python: Create a lambda function that adds 15 to a given number passed in as an argument

Python Lambda: Exercise-1 with Solution

Write a Python program to create a lambda function that adds 15 to a given number passed in as an argument, also create a lambda function that multiplies argument x with argument y and prints the result.

Sample Solution:

Python Code :

# Define a lambda function 'r' that takes a single argument 'a' and returns 'a + 15'
r = lambda a: a + 15

# Print the result of calling the lambda function 'r' with argument 10
print(r(10))

# Reassign 'r' to a new lambda function that takes two arguments 'x' and 'y' and returns their product
r = lambda x, y: x * y

# Print the result of calling the updated lambda function 'r' with arguments 12 and 4
print(r(12, 4))

Sample Output:

25
48

Explanation:

In the exercise above -

  • Lambda Function Creation:
  • r = lambda a: a + 15
    • This line creates a lambda function named r.
    • The lambda function takes a single argument a and returns a + 15.
    • This lambda function adds 15 to the arguments passed to it.
  • Lambda Function Invocation:
  • print(r(10))
    • The code calls the lambda function r with the argument 10.
    • It prints the result of invoking the lambda function with 10, which evaluates to 10 + 15 = 25.
  • Reassignment of r to a New Lambda Function:
  • r = lambda x, y: x * y
    • This line reassigns the variable r to a new lambda function.
    • The new lambda function takes two arguments x and y.
    • It returns the product of x and y (x * y).
  • Lambda Function Invocation with Multiple Arguments (Line 7):
  • print(r(12, 4))
    • This code calls the updated lambda function r with arguments 12 and 4.
    • It prints the result of invoking the lambda function with 12 and 4, which evaluates to 12 * 4 = 48.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Python Lambda Home.
Next: Write a Python program to create a function that takes one argument, and that argument will be multiplied with an unknown given number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.