Lambda Functions

Anonymous functions

Interview Relevant: Functional programming

Lambda Functions

Small anonymous functions.

Code Examples

Lambda anonymous functions.

python
1# Lambda syntax: lambda args: expression
2square = lambda x: x ** 2
3square(5)  # 25
4
5# Multiple arguments
6add = lambda a, b: a + b
7
8# With default values
9greet = lambda name="World": f"Hello, {name}!"
10
11# Common uses: sorting
12pairs = [(1, 'b'), (2, 'a'), (3, 'c')]
13sorted(pairs, key=lambda x: x[1])  # By second element
14
15# With map/filter
16nums = [1, 2, 3, 4, 5]
17list(map(lambda x: x**2, nums))    # [1, 4, 9, 16, 25]
18list(filter(lambda x: x > 2, nums)) # [3, 4, 5]
19
20# Immediately invoked
21result = (lambda x: x * 2)(5)  # 10

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In