0
0
Pythonprogramming~5 mins

Lambda syntax and behavior in Python

Choose your learning style9 modes available
Introduction

Lambdas let you write small, quick functions without naming them. They make your code shorter and easier to use for simple tasks.

When you need a quick function for a short task, like adding two numbers.
When you want to pass a simple function as an argument to another function.
When you want to create a function inside another function without naming it.
When you want to sort or filter data with a small custom rule.
When you want to keep your code clean by avoiding extra function names.
Syntax
Python
lambda arguments: expression

Lambdas can only have one expression, no multiple statements.

The expression result is automatically returned.

Examples
This lambda adds two numbers and prints 8.
Python
add = lambda x, y: x + y
print(add(3, 5))
This lambda squares a number and prints 16.
Python
square = lambda n: n * n
print(square(4))
This lambda adds 10 to 5 and prints 15 without naming the function.
Python
print((lambda x: x + 10)(5))
Sample Program

This program uses a lambda to square each number in a list and prints the new list.

Python
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x * x, numbers))
print(squared)
OutputSuccess
Important Notes

Lambdas are best for simple tasks; for complex logic, use regular functions.

They help keep code short and readable when used wisely.

Summary

Lambdas create quick, unnamed functions with one expression.

They are useful for short tasks like simple calculations or data processing.

Use lambdas to make your code cleaner and avoid extra function names.