PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Basics » Python Lambda Functions: Syntax, Examples, and Best Practices

Python Lambda Functions: Syntax, Examples, and Best Practices

Updated on: December 4, 2026 | Leave a Comment

A lambda function is a small, anonymous function written in a single expression. Instead of defining a full function with def, you can write lambda x: x * 2 right where you need it. Lambdas are most useful when you pass a short function to another function, for example to tell sorted() how to order items.

In this tutorial, you’ll learn the lambda syntax, how to use lambdas with Python’s built-in functions, how they capture variables, and when a regular function is the better choice.

Key terms used in this article:

  • Lambda function: An anonymous function created with the lambda keyword. It can contain only one expression.
  • Anonymous function: A function without a name.
  • Higher-order function: A function that takes another function as an argument or returns one, such as sorted(), map(), and filter().
  • Key function: A function that tells sorted(), min(), or max() what value to compare for each item.
  • Closure: An inner function that remembers variables from the scope where it was created.

Table of contents

  • Lambda syntax
  • Calling a lambda immediately
  • Lambda arguments
  • Conditional logic in a lambda
  • What lambdas cannot do
  • Using lambda with sorted()
    • Sorting lists of tuples and dictionaries
    • Sorting a dictionary by value
  • Using lambda with min() and max()
  • Using lambda with map()
  • Using lambda with filter()
  • Using lambda with reduce()
  • Lambda vs. list comprehension
  • Returning a lambda from a function (closures)
  • Lambdas in dictionaries (dispatch tables)
  • The late-binding trap
  • Alternatives to lambda in the standard library
  • When to use lambda and when to use def
  • Common mistakes
  • Practice exercises
  • Summary

Lambda syntax

lambda arguments: expressionCode language: Python (python)
  • lambda is the keyword that creates the function.
  • arguments is a comma-separated list of parameters. It can be empty.
  • expression is a single expression. Its value is returned automatically, so there’s no return keyword.

Here’s the same function written with def and with lambda:

def square(x):
    return x * x

square_lambda = lambda x: x * x

print(square(5))
print(square_lambda(5))
print(square_lambda.__name__)Code language: Python (python)

Output:

25
25
<lambda>

Both functions do the same thing. The lambda’s name shows as <lambda>, because a lambda is anonymous.

Style tip: Assigning a lambda to a variable, as in square_lambda = lambda x: x * x, works but is discouraged by PEP 8. If a function needs a name, use def. Lambdas are meant to be used inline, as arguments to other functions.

Calling a lambda immediately

You can define and call a lambda in one expression. This is mostly useful for understanding how lambdas work:

print((lambda x, y: x + y)(3, 4))Code language: Python (python)

Output:

7

Lambda arguments

Lambdas support the same kinds of parameters as regular functions.

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

# Multiple arguments
add = lambda a, b, c: a + b + c
print(add(1, 2, 3))

# Default values
power = lambda base, exp=2: base ** exp
print(power(4))
print(power(2, 10))

# Keyword arguments
full_name = lambda first, last: f"{first} {last}"
print(full_name(last="Doe", first="Jessa"))

# *args and **kwargs
total = lambda *nums: sum(nums)
print(total(1, 2, 3, 4))

describe = lambda **info: ", ".join(f"{k}={v}" for k, v in info.items())
print(describe(name="Kelly", age=30))Code language: Python (python)

Output:

Hello!
6
16
1024
Jessa Doe
10
name=Kelly, age=30

Conditional logic in a lambda

A lambda can’t contain an if statement, but it can use a conditional expression (value_if_true if condition else value_if_false):

parity = lambda n: "even" if n % 2 == 0 else "odd"
print(parity(4))
print(parity(7))

grade = lambda score: "A" if score >= 90 else "B" if score >= 75 else "C"
print(grade(95), grade(80), grade(60))Code language: Python (python)

Output:

even
odd
A B C

Nested conditional expressions get hard to read quickly. If you need more than two branches, a def function with if/elif is clearer.

What lambdas cannot do

Because a lambda is limited to one expression, you can’t use statements inside it:

  • No return, pass, assert, or raise statements
  • No assignments with = (the walrus operator := is allowed but rarely a good idea)
  • No loops written as statements (comprehensions are fine, because they’re expressions)
  • No docstrings or type annotations
# A comprehension is an expression, so this works
squares_up_to = lambda n: [i * i for i in range(1, n + 1)]
print(squares_up_to(5))Code language: Python (python)

Output:

[1, 4, 9, 16, 25]

Using lambda with sorted()

The most common use of a lambda is as a key function. sorted(), list.sort(), min(), and max() call the key function on each item and compare the results.

words = ["banana", "apple", "Cherry", "date"]

print(sorted(words))                              # uppercase sorts first
print(sorted(words, key=lambda w: w.lower()))     # case-insensitive
print(sorted(words, key=lambda w: len(w)))        # by length
print(sorted(words, key=lambda w: w[-1]))         # by last letterCode language: Python (python)

Output:

['Cherry', 'apple', 'banana', 'date']
['apple', 'banana', 'Cherry', 'date']
['date', 'apple', 'banana', 'Cherry']
['banana', 'apple', 'date', 'Cherry']

Sorting lists of tuples and dictionaries

students = [("Jessa", 88), ("Kelly", 95), ("Emma", 79), ("Brad", 95)]

# Sort by score, highest first
print(sorted(students, key=lambda s: s[1], reverse=True))

# Sort by score descending, then name ascending
print(sorted(students, key=lambda s: (-s[1], s[0])))

employees = [
    {"name": "Jessa", "salary": 7000},
    {"name": "Kelly", "salary": 9500},
    {"name": "Emma", "salary": 6200},
]
employees.sort(key=lambda e: e["salary"])
print([e["name"] for e in employees])Code language: Python (python)

Output:

[('Kelly', 95), ('Brad', 95), ('Jessa', 88), ('Emma', 79)]
[('Brad', 95), ('Kelly', 95), ('Jessa', 88), ('Emma', 79)]
['Emma', 'Jessa', 'Kelly']

Returning a tuple from the key function sorts by several fields at once. The negative sign reverses the order for a numeric field only.

Sorting a dictionary by value

stock = {"apples": 30, "bananas": 12, "cherries": 45}

by_value = dict(sorted(stock.items(), key=lambda item: item[1]))
print(by_value)Code language: Python (python)

Output:

{'bananas': 12, 'apples': 30, 'cherries': 45}

Using lambda with min() and max()

products = [("laptop", 1200), ("mouse", 25), ("monitor", 300)]

cheapest = min(products, key=lambda p: p[1])
priciest = max(products, key=lambda p: p[1])
print(cheapest)
print(priciest)

words = ["sun", "elephant", "tree"]
print(max(words, key=lambda w: len(w)))Code language: Python (python)

Output:

('mouse', 25)
('laptop', 1200)
elephant

Using lambda with map()

map(function, iterable) applies a function to every item and returns a lazy iterator. Wrap it in list() to see the results:

prices = [10, 25, 40]
with_tax = list(map(lambda p: round(p * 1.18, 2), prices))
print(with_tax)

names = ["jessa", "kelly", "emma"]
print(list(map(lambda n: n.title(), names)))

# map() with two iterables
a = [1, 2, 3]
b = [10, 20, 30]
print(list(map(lambda x, y: x + y, a, b)))Code language: Python (python)

Output:

[11.8, 29.5, 47.2]
['Jessa', 'Kelly', 'Emma']
[11, 22, 33]

Using lambda with filter()

filter(function, iterable) keeps only the items for which the function returns a truthy value:

numbers = [3, 8, 15, 22, 7, 40]

evens = list(filter(lambda n: n % 2 == 0, numbers))
print(evens)

words = ["python", "", "java", "  ", "go"]
non_blank = list(filter(lambda w: w.strip(), words))
print(non_blank)Code language: Python (python)

Output:

[8, 22, 40]
['python', 'java', 'go']

Using lambda with reduce()

functools.reduce() combines all items into a single value by applying a two-argument function cumulatively:

from functools import reduce

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

product = reduce(lambda acc, n: acc * n, numbers)
print(product)

largest = reduce(lambda a, b: a if a > b else b, numbers)
print(largest)

# With a starting value
total_chars = reduce(lambda acc, word: acc + len(word), ["hi", "hello", "hey"], 0)
print(total_chars)Code language: Python (python)

Output:

120
5
10

For simple cases, built-ins such as sum(), max(), and math.prod() are clearer than reduce().

Lambda vs. list comprehension

map() and filter() with a lambda can often be replaced by a list comprehension, which most Python developers find easier to read:

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

# map + filter with lambdas
result1 = list(map(lambda n: n * n, filter(lambda n: n % 2 == 0, numbers)))

# list comprehension
result2 = [n * n for n in numbers if n % 2 == 0]

print(result1)
print(result2)Code language: Python (python)

Output:

[4, 16, 36]
[4, 16, 36]

Use a comprehension when you’re building a new list. Use map() when you already have a named function, as in map(str.upper, names).

Returning a lambda from a function (closures)

A function can create and return a lambda. The lambda remembers the variables from the function that created it. This is called a closure:

def make_multiplier(factor):
    return lambda x: x * factor

double = make_multiplier(2)
triple = make_multiplier(3)

print(double(10))
print(triple(10))Code language: Python (python)

Output:

20
30

Lambdas in dictionaries (dispatch tables)

A dictionary of lambdas can replace a long if/elif chain:

operations = {
    "+": lambda a, b: a + b,
    "-": lambda a, b: a - b,
    "*": lambda a, b: a * b,
    "/": lambda a, b: a / b if b != 0 else "undefined",
}

for op in "+-*/":
    print(f"12 {op} 4 = {operations[op](12, 4)}")

print(operations["/"](5, 0))Code language: Python (python)

Output:

12 + 4 = 16
12 - 4 = 8
12 * 4 = 48
12 / 4 = 3.0
undefined

The late-binding trap

Lambdas look up variables when they’re called, not when they’re created. This causes a classic bug when you create lambdas in a loop:

funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])  # expected [0, 1, 2]Code language: Python (python)

Output:

[2, 2, 2]

All three lambdas see the final value of i, which is 2. To capture the current value, use a default argument, which is evaluated when the lambda is created:

funcs = [lambda i=i: i for i in range(3)]
print([f() for f in funcs])Code language: Python (python)

Output:

[0, 1, 2]

Alternatives to lambda in the standard library

The operator module has ready-made functions for the most common lambdas. They’re faster and often clearer:

Lambdaoperator equivalent
lambda x: x[1]operator.itemgetter(1)
lambda x: x["name"]operator.itemgetter("name")
lambda obj: obj.ageoperator.attrgetter("age")
lambda a, b: a + boperator.add
lambda a, b: a * boperator.mul
lambda s: s.lower()str.lower
from operator import itemgetter

students = [("Jessa", 88), ("Kelly", 95), ("Emma", 79)]
print(sorted(students, key=itemgetter(1)))

words = ["banana", "Apple", "cherry"]
print(sorted(words, key=str.lower))Code language: Python (python)

Output:

[('Emma', 79), ('Jessa', 88), ('Kelly', 95)]
['Apple', 'banana', 'cherry']

When to use lambda and when to use def

Use a lambda whenUse def when
The function is a short, one-line expressionThe logic needs several statements or branches
You pass it once as an argument (key=, map(), filter())You call it in several places
The meaning is obvious from the expressionIt needs a descriptive name, a docstring, or type hints
You want readable tracebacks (lambdas show up as <lambda>)

Common mistakes

  • Calling the lambda instead of passing it. sorted(items, key=(lambda x: x[1])(items)) is wrong. Pass the function itself: key=lambda x: x[1].
  • Forgetting list() around map() or filter(). In Python 3, both return lazy iterators, so print(map(...)) shows <map object ...>.
  • Using return inside a lambda. lambda x: return x is a SyntaxError. The expression’s value is returned automatically.
  • Late binding in loops. Use lambda x=x: ... to capture the current loop value.
  • Overusing lambdas. If you need to read a lambda twice to understand it, turn it into a named function.

Practice exercises

Exercise 1: Sort a list of words by their number of vowels, fewest first.

words = ["banana", "sky", "apple", "rhythm", "education"]
result = sorted(words, key=lambda w: sum(ch in "aeiou" for ch in w))
print(result)Code language: Python (python)

Output:

['sky', 'rhythm', 'apple', 'banana', 'education']

Exercise 2: Use filter() and a lambda to keep only the palindromes in a list.

words = ["level", "python", "radar", "noon", "code"]
palindromes = list(filter(lambda w: w == w[::-1], words))
print(palindromes)Code language: Python (python)

Output:

['level', 'radar', 'noon']

Exercise 3: Convert a list of Celsius temperatures to Fahrenheit using map() and a lambda.

celsius = [0, 21.5, 37, 100]
fahrenheit = list(map(lambda c: round(c * 9 / 5 + 32, 1), celsius))
print(fahrenheit)Code language: Python (python)

Output:

[32.0, 70.7, 98.6, 212.0]

Exercise 4: Find the student with the highest average score.

scores = {"Jessa": [80, 92, 88], "Kelly": [95, 90, 85], "Emma": [70, 99, 91]}
best = max(scores, key=lambda name: sum(scores[name]) / len(scores[name]))
print(best)Code language: Python (python)

Output:

Kelly

Summary

  • A lambda is an anonymous, single-expression function: lambda args: expression.
  • The expression’s value is returned automatically. Statements such as return, loops, and assignments aren’t allowed.
  • Lambdas are most useful as short key functions for sorted(), min(), and max(), and as arguments to map(), filter(), and reduce().
  • Lambdas can capture variables from the enclosing scope, but they look them up when called. Use default arguments to capture loop values.
  • Prefer list comprehensions over map()/filter() with lambdas, and prefer def for anything longer than one simple expression.

Also, See:

  • Python Functions
  • Python Function Arguments
  • List, Dict, and Set Comprehensions in Python
  • Python Lambda and Functional Programming Exercises

Filed Under: Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Basics
TweetF  sharein  shareP  Pin

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com