0
0
PythonHow-ToBeginner · 3 min read

How to Use Lambda in Python: Simple Guide with Examples

In Python, a lambda is a small anonymous function defined with the lambda keyword. It can take any number of arguments but has only one expression, which is returned automatically. Lambdas are useful for short, simple functions used temporarily.
📐

Syntax

A lambda function is written as lambda arguments: expression. The arguments are inputs like in normal functions, and the expression is a single calculation or operation whose result is returned automatically.

  • lambda: keyword to create the function
  • arguments: inputs separated by commas
  • expression: single output expression, no need for return
python
lambda x, y: x + y
💻

Example

This example shows how to create a lambda function to add two numbers and use it immediately.

python
add = lambda x, y: x + y
result = add(5, 3)
print(result)
Output
8
⚠️

Common Pitfalls

Common mistakes include trying to write multiple statements inside a lambda or forgetting that lambdas return the expression automatically. Also, lambdas are best for simple functions; complex logic should use regular functions.

python
# wrong = lambda x: (x += 1)  # SyntaxError: can't use assignment in lambda

# Correct way:
correct = lambda x: x + 1
print(correct(4))
Output
5
📊

Quick Reference

Use lambdas for short, simple functions without a name. They are often used with functions like map(), filter(), and sorted() for quick operations.

Use CaseExample
Add two numberslambda x, y: x + y
Square a numberlambda x: x ** 2
Filter even numbersfilter(lambda x: x % 2 == 0, numbers)
Sort by second itemsorted(items, key=lambda x: x[1])

Key Takeaways

A lambda is a small anonymous function with one expression and no name.
Use lambda arguments: expression to create it quickly.
Lambdas are great for short, simple tasks like in map or filter.
Avoid complex logic or multiple statements inside lambdas.
Remember lambdas return the expression automatically without return.