DEV Community

Tarun Sharma
Tarun Sharma

Posted on • Originally published at tapstechie.hashnode.dev on

1

Python Lambda Functions: Beginner-Friendly Overview

Explanation:

A lambda function in Python is a small anonymous function defined using the lambda keyword. It can take any number of arguments but can only have one expression. The expression is evaluated and returned.

Syntax:

lambda arguments: expression
Enter fullscreen mode Exit fullscreen mode

Example:

# A lambda function that adds 10 to the input
add_ten = lambda x: x + 10
print(add_ten(5))  # Output: 15
Enter fullscreen mode Exit fullscreen mode

Use Cases:

  • Short functions that are used once or a few times.

  • Used with higher-order functions like map(), filter(), and reduce().

Common Tricks:

  • Simplifying small functions:
def add(a, b):
    return a + b

 # Can be simplified as:
add = lambda a, b: a + b
Enter fullscreen mode Exit fullscreen mode
  • Using with map():
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
# squares will be [1, 4, 9, 16, 25]
Enter fullscreen mode Exit fullscreen mode
  • Using with filter():
numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
# even_numbers will be [2, 4]
Enter fullscreen mode Exit fullscreen mode
  • Using with reduce() from functools:
from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
# product will be 120
Enter fullscreen mode Exit fullscreen mode

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay