Tutorials Logic
Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

Lambda in Python — Anonymous Functions with Examples

What is a Lambda Function?

A lambda is a small, anonymous (unnamed) function defined in a single line. It can take any number of arguments but can only have one expression. The result of the expression is automatically returned.

Syntax: lambda arguments: expression

Basic Lambda Examples

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

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

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

multiply = lambda a, b, c: a * b * c
print(multiply(2, 3, 4))  # 24

# Lambda with condition
is_even = lambda n: n % 2 == 0
print(is_even(4))   # True
print(is_even(7))   # False

# Immediately invoked lambda
result = (lambda x, y: x + y)(10, 20)
print(result)  # 30

Lambda with sorted()

The most common use of lambda is as a key function for sorting.

Sorting with Lambda
# Sort by string length
words = ["banana", "apple", "cherry", "fig", "date"]
sorted_words = sorted(words, key=lambda w: len(w))
print(sorted_words)  # ['fig', 'date', 'apple', 'banana', 'cherry']

# Sort list of dicts by a field
students = [
    {"name": "Alice", "grade": 92},
    {"name": "Bob",   "grade": 85},
    {"name": "Charlie", "grade": 97},
]
by_grade = sorted(students, key=lambda s: s["grade"], reverse=True)
for s in by_grade:
    print(f"{s['name']}: {s['grade']}")
# Charlie: 97
# Alice: 92
# Bob: 85

# Sort tuples by second element
pairs = [(1, 3), (2, 1), (3, 2)]
pairs.sort(key=lambda p: p[1])
print(pairs)  # [(2, 1), (3, 2), (1, 3)]

Lambda with map(), filter(), reduce()

map, filter, reduce
numbers = [1, 2, 3, 4, 5, 6, 7, 8]

# map() - apply function to every item
squares = list(map(lambda x: x**2, numbers))
print(squares)   # [1, 4, 9, 16, 25, 36, 49, 64]

# filter() - keep items where function returns True
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)     # [2, 4, 6, 8]

# reduce() - accumulate to a single value
from functools import reduce
product = reduce(lambda acc, x: acc * x, numbers)
print(product)   # 40320 (8!)

total = reduce(lambda acc, x: acc + x, numbers)
print(total)     # 36

# Note: list comprehensions are often preferred over map/filter
squares_comp = [x**2 for x in numbers]
evens_comp = [x for x in numbers if x % 2 == 0]

Lambda vs Regular Function

FeatureLambdadef Function
NameAnonymousNamed
LinesSingle lineMultiple lines
StatementsExpression onlyAny statements
DocstringNoYes
Best forShort, throwaway functionsReusable, complex logic
When to Use Lambda
# Good use: short key function inline
data = [{"x": 3}, {"x": 1}, {"x": 2}]
data.sort(key=lambda d: d["x"])

# Good use: simple callback
buttons = ["OK", "Cancel", "Help"]
actions = {btn: lambda b=btn: print(f"Clicked: {b}") for btn in buttons}
actions["OK"]()  # Clicked: OK

# Bad use: complex logic (use def instead)
# Avoid this:
process = lambda x: x**2 if x > 0 else -x if x < 0 else 0

# Better as a named function:
def process(x):
    if x > 0:
        return x ** 2
    elif x < 0:
        return -x
    return 0

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.