Python Lambda

Learn about lambda functions in Python - small anonymous functions that can have any number of arguments.

Lambda Functions

A lambda function is a small anonymous function.

A lambda function can take any number of arguments, but can only have one expression.

Syntax

lambda arguments : expression

The expression is executed and the result is returned:

Example - Add 10 to argument a, and return the result:

x = lambda a : a + 10
print(x(5))

Lambda functions can take any number of arguments:

Example - Multiply argument a with argument b and return the result:

x = lambda a, b : a * b
print(x(5, 6))

Example - Summarize argument a, b, and c and return the result:

x = lambda a, b, c : a + b + c
print(x(5, 6, 2))

Why Use Lambda Functions?

The power of lambda is better shown when you use them as an anonymous function inside another function.

Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number:

Example

def myfunc(n):
    return lambda a : a * n

Use that function definition to make a function that always doubles the number you send in:

Example

def myfunc(n):
    return lambda a : a * n

mydoubler = myfunc(2)

print(mydoubler(11))

Or, use the same function definition to make a function that always triples the number you send in:

Example

def myfunc(n):
    return lambda a : a * n

mytripler = myfunc(3)

print(mytripler(11))

Or, use the same function definition to make both functions, in the same program:

Example

def myfunc(n):
    return lambda a : a * n

mydoubler = myfunc(2)
mytripler = myfunc(3)

print(mydoubler(11))
print(mytripler(11))

Use lambda functions when an anonymous function is required for a short period of time.

Lambda with Built-in Functions

Using Lambda with map()

The map() function applies a function to every item in an iterable:

Example

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

Using Lambda with filter()

The filter() function filters items from an iterable based on a condition:

Example

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # [2, 4, 6, 8, 10]

Using Lambda with reduce()

The reduce() function applies a function cumulatively to items in an iterable:

Example

from functools import reduce

numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product)  # 120 (1*2*3*4*5)

Using Lambda with sorted()

Lambda functions are useful for custom sorting:

Example

students = [('Alice', 85), ('Bob', 90), ('Charlie', 78)]

# Sort by grade (second element)
sorted_by_grade = sorted(students, key=lambda x: x[1])
print(sorted_by_grade)

# Sort by name length
sorted_by_name_length = sorted(students, key=lambda x: len(x[0]))
print(sorted_by_name_length)

Practical Examples

Temperature Conversion

# Convert Celsius to Fahrenheit
celsius_to_fahrenheit = lambda c: (c * 9/5) + 32

temperatures_c = [0, 20, 30, 100]
temperatures_f = list(map(celsius_to_fahrenheit, temperatures_c))
print(temperatures_f)  # [32.0, 68.0, 86.0, 212.0]

String Processing

words = ["python", "lambda", "function", "programming"]

# Capitalize all words
capitalized = list(map(lambda x: x.capitalize(), words))
print(capitalized)

# Filter words longer than 6 characters
long_words = list(filter(lambda x: len(x) > 6, words))
print(long_words)

Mathematical Operations

# Create a list of mathematical operations
operations = {
    'add': lambda x, y: x + y,
    'subtract': lambda x, y: x - y,
    'multiply': lambda x, y: x * y,
    'divide': lambda x, y: x / y if y != 0 else 'Cannot divide by zero'
}

print(operations['add'](10, 5))      # 15
print(operations['multiply'](4, 3))  # 12

Conditional Lambda

# Lambda with conditional expression
max_value = lambda a, b: a if a > b else b
print(max_value(10, 20))  # 20

# Check if number is even or odd
check_even = lambda x: "Even" if x % 2 == 0 else "Odd"
print(check_even(7))   # Odd
print(check_even(8))   # Even

Lambda vs Regular Functions

Lambda Functions

  • Anonymous (no name)
  • Single expression only
  • Automatically return the result
  • Good for simple operations
  • Often used with map(), filter(), reduce()
# Lambda function
square = lambda x: x**2

Regular Functions

  • Named functions
  • Multiple statements allowed
  • Explicit return statement needed
  • Good for complex operations
  • More readable for complex logic
# Regular function
def square(x):
    return x**2

Best Practices

  • Use lambda for simple, one-line functions
  • Prefer regular functions for complex logic
  • Lambda functions are great with functional programming concepts
  • Don't assign lambda to variables; use def instead
  • Use lambda when you need a function for a short period

Where Lambdas Shine: sort, map, filter

Lambdas are most useful as the key or transform argument to higher-order functions.

people = [("Ann", 30), ("Bob", 25), ("Cara", 35)]

people.sort(key=lambda p: p[1])          # sort by age
print(people)   # [('Bob', 25), ('Ann', 30), ('Cara', 35)]

nums = [1, 2, 3, 4]
print(list(map(lambda x: x * x, nums)))       # [1, 4, 9, 16]
print(list(filter(lambda x: x % 2 == 0, nums)))  # [2, 4]

A list comprehension is often clearer than map/filter with a lambda: [x*x for x in nums] beats map(lambda x: x*x, nums).

lambda vs def

lambdadef
BodySingle expressionAny number of statements
NameAnonymousNamed
Best forShort throwaway logicReusable, documented logic

Do not assign a lambda to a variable just to name it — use def instead. Lambdas are for inline, throwaway use.

Try It Yourself

Exercise 1: Sort ["bbb", "a", "cc"] by string length using a lambda.

Show solution
words = ["bbb", "a", "cc"]
print(sorted(words, key=lambda w: len(w)))   # ['a', 'cc', 'bbb']

Exercise 2: Use map with a lambda to add 10 to every number in [1, 2, 3].

Show solution
print(list(map(lambda x: x + 10, [1, 2, 3])))   # [11, 12, 13]

Key Takeaways

  • A lambda is a one-expression anonymous function.
  • Great as the key for sort/sorted, and with map/filter.
  • Prefer def or a comprehension when logic is longer or reused.

📘 Real-World Deep Dive

Lambdas are anonymous functions meant for throw-away use — <code>sorted</code>/<code>map</code>/<code>filter</code> key arguments, or short callbacks. Anything longer than one line belongs in a named <code>def</code>.

Real-Life Scenario

A practical sorting/ranking UI where lambdas power <code>key=</code> — and we switch to <code>attrgetter</code> / <code>itemgetter</code> when speed matters.

Real-Life Example

from operator import itemgetter, attrgetter

users = [
    {"name": "Ada",  "joined": "2024-01-12", "score": 412},
    {"name": "Bob",  "joined": "2025-06-30", "score": 198},
    {"name": "Cy",   "joined": "2024-11-01", "score": 305},
    {"name": "De",   "joined": "2026-02-19", "score": 102},
]

# By name ascending
print("by name :", [*sorted(users, key=lambda u: u["name"])])
# By joined ascending
print("by date :", [*sorted(users, key=lambda u: u["joined"])])
# By score descending with tiebreaker
print("by score:", [*sorted(users, key=lambda u: (-u["score"], u["name"]))])

# Equivalent with itemgetter (faster, less opaque)
print("by name (itemgetter) :", [*sorted(users, key=itemgetter("name"))])

Expected Output

by name : [{'name': 'Ada', 'joined': '2024-01-12', 'score': 412}, ...]
by date : [...]
by score: [...]
by name (itemgetter) : [{'name': 'Ada', ...}]

Common mistakes

  • Pythons lambda doesn't allow statements; if you need branching, name it.
  • Heavy use of lambdas hurts readability — if a lambda is referenced twice, give it a name.
  • A lambda assigned to a variable is just a less-clear def; use def instead.

🚀 Performance & Best Practices

  • itemgetter / attrgetter beat lambda in key= by ~20%.
  • In map/filter prefer comprehensions unless the operator is genuinely inline-only.
  • Pre-compute keys before sorting a huge list: xs.sort(key=fn) caches keys per element.

🧪 Try It Yourself

  1. Refactor one of the sorts to use attrgetter on a dataclass.
  2. Bench sort(key=lambda) vs. sort(key=attrgetter) on 1 M records.
  3. Replace a chain of filter/map with a list comprehension.

FAQ: Python Lambda

Common questions about this page.

What is Python Lambda?

Python Lambda is a Python Tutorial lesson that explains python lambda in Python. Learn about lambda functions in Python - small anonymous functions that can have any number of arguments. Copy the samples and run them in the Python editor. It is written for beginners who want a clear definition and working examples.

Should I run python lambda examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn python lambda in this Python Tutorial Python lesson (Python Lambda).

How do I use python lambda in Python?

To use python lambda in Python, follow the examples on this StudyGrid page. Copy a snippet, run it in the browser, then Download and run it locally for better learning. Change the values and compare the output.

What is the syntax of python lambda?

This Python Lambda tutorial shows python lambda syntax with short Python examples. Use the code blocks in this lesson for the exact statements, then try them in your editor.

Python Lambda example for beginners

Yes. This page includes a beginner python lambda example you can copy and run. It is designed for searches such as "python lambda for beginners", "python lambda example", and "how to use python lambda".

What are common mistakes with python lambda?

Common python lambda mistakes include wrong syntax, mixing types, and skipping practice. Work through this Python Tutorial chapter in order, run every example, and check the output before moving on.

Why should I learn python lambda?

Python Lambda is used in real Python work. Learning python lambda helps you write clearer programs and continue the Python Tutorial tutorial on StudyGrid.

Is Python Lambda free to learn online?

Yes. You can learn python lambda free on StudyGrid (studygrid.in). This chapter is part of the Python Tutorial path and includes examples, syntax, and next-step links.