Ad – 728Γ—90
βš™οΈ Functions

Python Lambda Functions – The Complete Guide

A lambda function is a small, anonymous function defined in a single line using the lambda keyword. Unlike regular functions defined with def, lambdas don't have a name, and their body is a single expression. They're incredibly useful for short operations, especially when passed to higher-order functions like map(), filter(), and sorted().

⏱️ 18 min read 🎯 Intermediate πŸ“… Updated 2026

Lambda Syntax

The syntax for a lambda function is:

Python
lambda arguments: expression

# vs a regular function
def function_name(arguments):
    return expression

Key rules:

  • Can take any number of arguments but only one expression
  • The expression is automatically returned β€” no return keyword
  • Cannot contain statements (if/else blocks, loops, assignments)
  • Can use conditional expressions (ternary): x if condition else y

Basic Lambda Examples

Python
# Regular function
def square(x):
    return x ** 2

# Equivalent lambda
square = lambda x: x ** 2

print(square(5))   # 25
print(square(10))  # 100

# Multiple arguments
add = lambda a, b: a + b
print(add(3, 7))   # 10

# No arguments
greet = lambda: "Hello, World!"
print(greet())     # Hello, World!

# With conditional expression
absolute = lambda x: x if x >= 0 else -x
print(absolute(-5))  # 5
print(absolute(3))   # 3
β–Ά Output
25 100 10 Hello, World! 5 3

Lambda with map()

map(function, iterable) applies a function to every item in an iterable. Lambda is perfect here:

Python
numbers = [1, 2, 3, 4, 5]

# Square every number
squares = list(map(lambda x: x ** 2, numbers))
print(squares)  # [1, 4, 9, 16, 25]

# Convert temperatures from Celsius to Fahrenheit
celsius = [0, 20, 37, 100]
fahrenheit = list(map(lambda c: (c * 9/5) + 32, celsius))
print(fahrenheit)  # [32.0, 68.0, 98.6, 212.0]

# Capitalize all strings
names = ["alice", "bob", "charlie"]
capitalized = list(map(lambda s: s.capitalize(), names))
print(capitalized)  # ['Alice', 'Bob', 'Charlie']
β–Ά Output
[1, 4, 9, 16, 25] [32.0, 68.0, 98.6, 212.0] ['Alice', 'Bob', 'Charlie']

Lambda with filter()

filter(function, iterable) keeps only items where the function returns True:

Python
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Keep only even numbers
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # [2, 4, 6, 8, 10]

# Keep numbers greater than 5
greater = list(filter(lambda x: x > 5, numbers))
print(greater)  # [6, 7, 8, 9, 10]

# Filter non-empty strings
words = ["hello", "", "world", "", "python"]
non_empty = list(filter(lambda s: s, words))
print(non_empty)  # ['hello', 'world', 'python']

# Filter based on length
long_words = list(filter(lambda w: len(w) > 4, words))
print(long_words)  # ['hello', 'world', 'python']
Ad – 336Γ—280

Lambda with sorted()

The key parameter in sorted() accepts a function β€” lambda makes this concise:

Python
# Sort by string length
fruits = ["banana", "apple", "fig", "cherry", "kiwi"]
by_length = sorted(fruits, key=lambda s: len(s))
print(by_length)  # ['fig', 'kiwi', 'apple', 'banana', 'cherry']

# Sort in reverse
by_length_desc = sorted(fruits, key=lambda s: len(s), reverse=True)
print(by_length_desc)  # ['banana', 'cherry', 'apple', 'kiwi', 'fig']

# Sort list of tuples by second element
points = [(1, 3), (4, 1), (2, 5), (3, 2)]
by_y = sorted(points, key=lambda p: p[1])
print(by_y)  # [(4, 1), (3, 2), (1, 3), (2, 5)]

# Sort list of dicts by a key
students = [
    {"name": "Alice", "grade": 88},
    {"name": "Bob", "grade": 95},
    {"name": "Charlie", "grade": 72}
]
by_grade = sorted(students, key=lambda s: s["grade"], reverse=True)
for s in by_grade:
    print(f"{s['name']}: {s['grade']}")
β–Ά Output
['fig', 'kiwi', 'apple', 'banana', 'cherry'] ['banana', 'cherry', 'apple', 'kiwi', 'fig'] [(4, 1), (3, 2), (1, 3), (2, 5)] Bob: 95 Alice: 88 Charlie: 72

Lambda vs def – When to Use Which

SituationUse LambdaUse def
Simple one-line expressionβœ…Overkill
Passed inline to another functionβœ…Possible but verbose
Multiple lines of logic❌ Not possibleβœ…
Needs a docstringβŒβœ…
Reused multiple times❌ (use def for clarity)βœ…
Error handling (try/except)βŒβœ…
Key in sorted()/min()/max()βœ…Possible
πŸ’‘
PEP 8 Guideline on Lambda

Avoid assigning a lambda to a variable (f = lambda x: x+1) β€” that's what def is for. Use lambda anonymously, inline, where a function object is needed temporarily.

Advanced Lambda Patterns

Python
from functools import reduce

# Lambda with reduce() β€” sum all numbers
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda acc, x: acc + x, numbers)
print(total)  # 15

# Lambda returning another lambda (currying)
multiply = lambda x: (lambda y: x * y)
double = multiply(2)
triple = multiply(3)
print(double(5))   # 10
print(triple(5))   # 15

# Lambda in a dictionary (dispatch table)
operations = {
    'add': lambda a, b: a + b,
    'sub': lambda a, b: a - b,
    'mul': lambda a, b: a * b,
    'div': lambda a, b: a / b if b != 0 else "Error: division by zero"
}

result = operations['mul'](6, 7)
print(result)  # 42

πŸ‹οΈ Practical Exercise

  1. Use map() and lambda to convert a list of prices (floats) to strings with a "$" prefix.
  2. Use filter() and lambda to extract all negative numbers from a list.
  3. Sort a list of dictionaries representing products by price (lowest first).
  4. Use reduce() and lambda to find the product (multiplication) of all elements in a list.

πŸ”₯ Challenge Exercise

Build a mini functional data pipeline using only lambdas and higher-order functions. Given a list of raw employee records (dicts with name, salary, department), use lambda + filter to get only Engineering dept, lambda + map to give them a 10% raise, and lambda + sorted to sort by new salary. Print the final list.

Interview Questions

  • What is a lambda function in Python? How is it different from a regular function?
  • Can a lambda function have multiple lines? Why or why not?
  • What are the common use cases for lambda functions?
  • What is the difference between map() and filter()? Give examples with lambda.
  • What does the sorted() key parameter do? Provide a lambda example.
  • When should you prefer def over lambda? What does PEP 8 say about it?
  • Can lambda functions access variables from the enclosing scope (closures)?

πŸ“‹ Summary

  • Lambda creates an anonymous function: lambda args: expression
  • The expression is automatically returned β€” no return needed
  • Best used inline with map(), filter(), sorted(), and reduce()
  • Cannot contain multiple statements, loops, or assignments
  • Can use ternary expressions: lambda x: x if x > 0 else 0
  • PEP 8 recommends using def when assigning to a variable name

Frequently Asked Questions

Can a lambda function have a default parameter? +

Yes: lambda x, y=10: x + y. The second parameter defaults to 10 if not provided.

Can you use *args or **kwargs in a lambda? +

Yes: lambda *args: sum(args) and lambda **kwargs: kwargs are both valid. This lets lambdas accept variable arguments.

Is a list comprehension faster than map() + lambda? +

Generally yes β€” list comprehensions are slightly faster and more Pythonic for most cases. Use [x**2 for x in nums] over list(map(lambda x: x**2, nums)). Use map+lambda when you already have a named function to pass in.