Friday, 27 December 2024

Python Lambda Function and challenges to solve

lambda function in Python is a small, anonymous function defined with the lambda keyword. It can have any number of arguments but only one expression. The result of the expression is automatically returned. 

Lambda functions are often used with higher-order functions like map()filter()sorted(), etc.

Key Points:

• Anonymous: Lambda functions don’t need a name.

• Concise: They’re typically used for simple, one-liner functions.

• Useful: Often used in data transformations, filtering, and sorting


Syntax:

lambda arguments: expression
  • arguments are the parameters passed to the function.

  • expression is evaluated and returned when the lambda function is called.


Lambda Function with a Single Argument

square = lambda x: x * x print(square(4)) # Output: 16

Lambda Function with a Two Argument

add = lambda x, y: x + y print(add(2, 3)) # Output: 5

Try-out Some Challenges to Practice Lambda Functions

  1. Write a lambda function that takes a first name and last name and combines them into a full name.

  2. Write a lambda function that takes a number and returns True if a number is even, otherwise False.

  3. Write a lambda function that takes string to check if a string is a palindrome (reads the same forward and backward).

  4. Write a lambda function that takes list of numbers to multiply each element of a list by 3 and return a new list.

  5. Given a list of strings, write a lambda function to sort the strings by their length. words = ["apple", "bat", "cherry", "date"]

Solutions:

  1. Write a lambda function that takes a first name and last name and combines them into a full name.

    full_name = lambda first, last: f"{first} {last}" print(full_name("John", "Doe")) # Output: "John Doe"
  2. Write a lambda function that takes a number and returns True if a number is even, otherwise False.

    is_even = lambda x: x%2==0 print(is_even(7)) # Output: False print(is_even(8)) # Output: True
  3. Write a lambda function that takes string to check if a string is a palindrome (reads the same forward and backward).

    is_palindrome = lambda s: s == s[::-1] print(is_palindrome("racecar")) # Output: True print(is_palindrome("hello")) # Output: False
  4. Write a lambda function that takes list of numbers to multiply each element of a list by 3 and return a new list.

    nums = [1, 2, 3, 4] multiply_by_3 = list(map(lambda x: x * 3, nums)) print(multiply_by_3) # Output: [3, 6, 9, 12]
  5. Given a list of strings, write a lambda function to sort the strings by their length. words = ["apple", "bat", "cherry", "date"]

    words = ["apple", "bat", "cherry", "date"] sort_by_length = sorted(words, key=lambda word: len(word)) print(sort_by_length) # Output: ['bat', 'date', 'apple', 'cherry']