← Back to Python

All Topics

Advertisement

Learn/Python/Python Fundamentals

Lambda Functions

Topic: Functions

Advertisement

Introduction

Lambda functions are small anonymous functions defined with the lambda keyword.

Basic Syntax

# Lambda function
square = lambda x: x ** 2
print(square(5))  # 25

# Multiple arguments
add = lambda x, y: x + y
print(add(3, 4))  # 7

# No arguments
get_pi = lambda: 3.14159

Common Use Cases

# Sorting
students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
students.sort(key=lambda x: x[1])  # Sort by grade

# Map
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))

# Filter
evens = list(filter(lambda x: x % 2 == 0, numbers))

# Reduce
from functools import reduce
product = reduce(lambda x, y: x * y, numbers)

Lambda vs Regular Functions

AspectLambdaRegular Function
SyntaxSingle expressionMultiple statements
NameAnonymousNamed
ReturnImplicitExplicit
Use caseShort operationsComplex logic

Practice Problems

  1. Use lambda with sorted() for custom sorting
  2. Create lambda functions for mathematical operations
  3. Use map() with lambda for data transformation
  4. Filter a list of dictionaries using lambda
  5. Combine lambda with reduce() for aggregation

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →