B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP Python Lambda Function Explained with Examples | LiveCodeProgramming
Python Installation First Python Program Control Flow if...else nested if else match-case logical-operators for loops while loops break / continue Functions Defining Functions Function Arguments Function return value Lambda Function Recursion Exception Handling Exception Handling Try Except Else and Finally Raise Exception Custom Exceptions File Handling File in python Read File Write File Append File Delete File Exception Handling

Python Lambda Function

A lambda function in Python is a small, anonymous function defined with the lambda keyword. It can take any number of arguments but can have only one expression. Lambda functions are useful when a short, throwaway function is needed.

Python में lambda function एक छोटा, गुमनाम function होता है जिसे lambda keyword से बनाया जाता है। यह कई arguments ले सकता है लेकिन केवल एक expression हो सकता है। जब short और temporary function चाहिए, तब इसका उपयोग किया जाता है।

Why Use Lambda Functions?
  • To write short functions without naming them
  • Useful inside functions like map(), filter(), reduce()
  • Improves code readability in concise operations
  • Short और बिना नाम के functions लिखने के लिए
  • map(), filter(), reduce() जैसी functions में उपयोगी
  • Code को छोटा और readable बनाता है
Lambda Function Examples
  1. Add 2 numbers
    add = lambda a, b: a + b
    print(add(5, 3))
    Output:
    8
  2. Square of a number
    square = lambda x: x * x
    print(square(6))
    Output:
    36
  3. Check even number
    is_even = lambda x: x % 2 == 0
    print(is_even(4))
    Output:
    True
  4. Sort list by second element of tuple
    pairs = [(1, 5), (2, 3), (4, 1)]
    pairs.sort(key=lambda x: x[1])
    print(pairs)
    Output:
    [(4, 1), (2, 3), (1, 5)]
  5. Use with map()
    nums = [1, 2, 3]
    squares = list(map(lambda x: x*x, nums))
    print(squares)
    Output:
    [1, 4, 9]
  6. Use with filter()
    nums = [1, 2, 3, 4]
    evens = list(filter(lambda x: x%2==0, nums))
    print(evens)
    Output:
    [2, 4]
  7. Use with reduce()
    from functools import reduce
    nums = [1, 2, 3, 4]
    product = reduce(lambda x, y: x * y, nums)
    print(product)
    Output:
    24
  8. Maximum of two numbers
    maximum = lambda a, b: a if a > b else b
    print(maximum(10, 15))
    Output:
    15
  9. Convert Celsius to Fahrenheit
    c_to_f = lambda c: (c * 9/5) + 32
    print(c_to_f(0))
    Output:
    32.0
  10. Return length of string
    length = lambda s: len(s)
    print(length("Python"))
    Output:
    6