Search This Blog

Monday, 21 July 2025

Python Basics: Lambdas

 

Lambdas in Python are like mini-functions without a name, perfect for short, quick operations—think of them as the “Post-it notes” of the coding world: compact, purposeful, and disposable.

What Is a Lambda Function?

A lambda in Python is an anonymous function defined using the lambda keyword. It’s used when you need a simple function for a short period and don’t want to formally define it with def.

Syntax Breakdown

lambda arguments: expression

  • You can pass multiple arguments, but only a single expression.
  • You can’t use statements like loops or conditionals—just expressions.


def traditional_square(num):
    return num * num

square = lambda num: num * num  #defined the function
print(square(5))


Common Use Cases

Use Case

Example

        With map()    

        map(lambda x: x*2, [1, 2, 3])[2, 4, 6]

        With filter()

        filter(lambda x: x > 0, [-1, 0, 1])[1]

        With sorted()

        sorted(words, key=lambda x: len(x)) → sort by length

        Quick function

        lambda x, y: x + y



No comments:

Post a Comment