Python Lambda Function Explained With Examples

Python Lambda Function Explained With Examples

If you have been writing Python for a while, you have almost certainly come across a line of code that looks something like this:

python

square = lambda x: x ** 2

And if you are like most beginners, your first reaction was probably: “What is that? Why does it look so different? And when would I ever use it?”

Lambda functions are one of those Python features that look confusing at first but become completely natural once you understand the idea behind them. They are compact, elegant, and genuinely useful especially in data science and functional programming contexts.

In this guide, we will break down Python lambda functions from the ground up from what they are, how they work, how they compare to regular functions, when to use them, and when not to with clear, practical examples.

What Is a Lambda Function in Python?

A lambda function is a small, anonymous function defined in a single line using the lambda keyword.

The word “anonymous” means it does not have a name — at least not in the way regular functions defined with def have names. It is a function you create on the fly, often for a short-lived purpose, without the formality of a full function definition.

Simple Analogy

Think of a lambda function like a sticky note compared to a printed document.

A regular function (defined with def) is like a printed document — formal, named, filed away, and meant to be referenced repeatedly.

A lambda function is like a sticky note — quick to write, used for a specific moment, and often discarded after use.

Both convey information. One is more permanent and formal. The other is quick and disposable.

Lambda Function Syntax

python

lambda arguments: expression
  • lambda — The keyword that tells Python you are creating a lambda function
  • arguments — One or more input parameters (just like a regular function)
  • expression — A single expression that is evaluated and returned automatically

Key rules:

  • Lambda functions can have any number of arguments
  • Lambda functions contain exactly one expression — no multiple lines, no statements
  • The result of the expression is automatically returned — no return keyword needed
  • Lambda functions can be assigned to a variable or used inline

Your First Lambda Function

Regular Function vs Lambda

python

# Regular function using def
def square_regular(x):
    return x ** 2

# Lambda function — same logic
square_lambda = lambda x: x ** 2

# Both work identically
print(square_regular(5))   # Output: 25
print(square_lambda(5))    # Output: 25
print(type(square_lambda)) # Output: <class 'function'>

Both functions do exactly the same thing. The lambda version is simply more compact.

Calling a Lambda Function Immediately

You can call a lambda function the moment you define it without assigning it to a variable first.

python

# Define and call immediately
result = (lambda x: x ** 2)(5)
print(result)  # Output: 25

# With two arguments
result = (lambda x, y: x + y)(3, 7)
print(result)  # Output: 10

This pattern defining and immediately calling is less common in everyday code but appears frequently in functional programming contexts.

Lambda Functions With Different Numbers of Arguments

No Arguments

python

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

One Argument

python

double = lambda x: x * 2
cube = lambda x: x ** 3
is_even = lambda x: x % 2 == 0
to_upper = lambda s: s.upper()

print(double(7))      # Output: 14
print(cube(4))        # Output: 64
print(is_even(8))     # Output: True
print(to_upper("hello"))  # Output: HELLO

Two Arguments

python

add = lambda x, y: x + y
multiply = lambda x, y: x * y
power = lambda base, exp: base ** exp
full_name = lambda first, last: f"{first} {last}"

print(add(3, 4))              # Output: 7
print(multiply(6, 7))         # Output: 42
print(power(2, 10))           # Output: 1024
print(full_name("Alice", "Johnson"))  # Output: Alice Johnson

Multiple Arguments

python

calculate_total = lambda price, quantity, discount: (price * quantity) * (1 - discount)

total = calculate_total(50, 3, 0.1)
print(f"Total: ${total:.2f}")  # Output: Total: $135.00

Default Arguments

python

greet_person = lambda name, greeting="Hello": f"{greeting}, {name}!"

print(greet_person("Alice"))           # Output: Hello, Alice!
print(greet_person("Bob", "Welcome"))  # Output: Welcome, Bob!

*args — Variable Number of Arguments

python

sum_all = lambda *args: sum(args)

print(sum_all(1, 2, 3))          # Output: 6
print(sum_all(10, 20, 30, 40))   # Output: 100

Lambda With Conditional Logic

Lambda functions can include conditional expressions using Python’s ternary operator but only one expression, which can itself contain a condition.

Single Condition

python

# Return absolute value
absolute = lambda x: x if x >= 0 else -x

print(absolute(5))   # Output: 5
print(absolute(-8))  # Output: 8

# Classify as positive or negative
classify = lambda x: "Positive" if x > 0 else "Negative" if x < 0 else "Zero"

print(classify(10))   # Output: Positive
print(classify(-3))   # Output: Negative
print(classify(0))    # Output: Zero

Grade Classifier

python

grade = lambda score: (
    "A" if score >= 90 else
    "B" if score >= 80 else
    "C" if score >= 70 else
    "D" if score >= 60 else
    "F"
)

print(grade(95))  # Output: A
print(grade(83))  # Output: B
print(grade(71))  # Output: C
print(grade(55))  # Output: F

Salary Band Classifier

python

salary_band = lambda salary: (
    "Executive" if salary >= 150000 else
    "Senior" if salary >= 100000 else
    "Mid-Level" if salary >= 60000 else
    "Junior"
)

print(salary_band(175000))  # Output: Executive
print(salary_band(95000))   # Output: Senior
print(salary_band(55000))   # Output: Junior

Lambda With map()

The map() function applies a function to every element in an iterable. Lambda and map() are one of the most natural and common combinations in Python.

Syntax

python

map(function, iterable)

Basic Examples

python

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

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

# Double every number
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)
# Output: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

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

Mapping Over Strings

python

names = ["alice", "bob", "charlie", "diana"]

# Capitalize all names
capitalized = list(map(lambda name: name.capitalize(), names))
print(capitalized)
# Output: ['Alice', 'Bob', 'Charlie', 'Diana']

# Get length of each name
lengths = list(map(lambda name: len(name), names))
print(lengths)
# Output: [5, 3, 7, 5]

# Create greeting for each name
greetings = list(map(lambda name: f"Hello, {name.capitalize()}!", names))
print(greetings)
# Output: ['Hello, Alice!', 'Hello, Bob!', 'Hello, Charlie!', 'Hello, Diana!']

Mapping Over a List of Dictionaries

python

employees = [
    {"name": "Alice", "salary": 95000},
    {"name": "Bob", "salary": 62000},
    {"name": "Charlie", "salary": 88000},
    {"name": "Diana", "salary": 55000}
]

# Apply 10% raise to all salaries
updated = list(map(
    lambda emp: {**emp, "salary": emp["salary"] * 1.10},
    employees
))

for emp in updated:
    print(f"{emp['name']}: ${emp['salary']:,.0f}")

# Output:
# Alice: $104,500
# Bob: $68,200
# Charlie: $96,800
# Diana: $60,500

map() With Two Iterables

python

prices = [100, 200, 300, 400]
quantities = [5, 3, 8, 2]

# Calculate total for each item
totals = list(map(lambda p, q: p * q, prices, quantities))
print(totals)
# Output: [500, 600, 2400, 800]

Lambda With filter() — Select Matching Elements

The filter() function keeps only the elements from an iterable for which the function returns True.

Syntax

python

filter(function, iterable)

Basic Examples

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)
# Output: [2, 4, 6, 8, 10]

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

# Keep only positive numbers
mixed = [-5, -3, 0, 2, 4, -1, 8, -7, 6]
positives = list(filter(lambda x: x > 0, mixed))
print(positives)
# Output: [2, 4, 8, 6]

Filtering Strings

python

words = ["apple", "banana", "cherry", "date", "elderberry", "fig"]

# Keep words longer than 5 characters
long_words = list(filter(lambda w: len(w) > 5, words))
print(long_words)
# Output: ['banana', 'cherry', 'elderberry']

# Keep words that start with a vowel
vowel_words = list(filter(lambda w: w[0] in 'aeiou', words))
print(vowel_words)
# Output: ['apple', 'elderberry']

Filtering Dictionaries

python

employees = [
    {"name": "Alice", "department": "Engineering", "salary": 95000, "active": True},
    {"name": "Bob", "department": "Marketing", "salary": 62000, "active": False},
    {"name": "Charlie", "department": "Engineering", "salary": 88000, "active": True},
    {"name": "Diana", "department": "HR", "salary": 55000, "active": True},
    {"name": "Eve", "department": "Sales", "salary": 71000, "active": False}
]

# Keep only active employees
active = list(filter(lambda e: e["active"], employees))
print([e["name"] for e in active])
# Output: ['Alice', 'Charlie', 'Diana']

# Keep only Engineering employees with salary above 85000
senior_engineers = list(filter(
    lambda e: e["department"] == "Engineering" and e["salary"] > 85000,
    employees
))
print([e["name"] for e in senior_engineers])
# Output: ['Alice', 'Charlie']

# Keep high earners (salary above 70000)
high_earners = list(filter(lambda e: e["salary"] > 70000, employees))
print([(e["name"], e["salary"]) for e in high_earners])
# Output: [('Alice', 95000), ('Charlie', 88000)]

Lambda With reduce() — Aggregate to a Single Value

The reduce() function (from the functools module) applies a function cumulatively to items in an iterable reducing the entire iterable to a single value.

Syntax

python

from functools import reduce
reduce(function, iterable)

Basic Examples

python

from functools import reduce

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

# Sum all numbers
total = reduce(lambda x, y: x + y, numbers)
print(total)  # Output: 15

# Product of all numbers
product = reduce(lambda x, y: x * y, numbers)
print(product)  # Output: 120

# Find maximum value
maximum = reduce(lambda x, y: x if x > y else y, numbers)
print(maximum)  # Output: 5

# Concatenate strings
words = ["Python", "is", "awesome"]
sentence = reduce(lambda x, y: x + " " + y, words)
print(sentence)  # Output: Python is awesome

Using reduce() With a Starting Value

python

from functools import reduce

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

# Sum starting from 100
total = reduce(lambda x, y: x + y, numbers, 100)
print(total)  # Output: 115

# Build a running total list
running_total = reduce(lambda acc, x: acc + [acc[-1] + x], numbers, [0])
print(running_total)
# Output: [0, 1, 3, 6, 10, 15]

Lambda With sorted() — Custom Sorting

One of the most practical uses of lambda functions is providing a custom sort key to sorted() and list.sort().

Sorting Numbers

python

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

# Sort ascending (default)
asc = sorted(numbers, key=lambda x: x)
print(asc)  # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Sort descending
desc = sorted(numbers, key=lambda x: x, reverse=True)
print(desc)  # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1]

Sorting Strings

python

words = ["banana", "Apple", "cherry", "date", "Elderberry"]

# Sort alphabetically (case-insensitive)
sorted_words = sorted(words, key=lambda w: w.lower())
print(sorted_words)
# Output: ['Apple', 'banana', 'cherry', 'date', 'Elderberry']

# Sort by string length
by_length = sorted(words, key=lambda w: len(w))
print(by_length)
# Output: ['date', 'Apple', 'banana', 'cherry', 'Elderberry']

# Sort by last character
by_last = sorted(words, key=lambda w: w[-1].lower())
print(by_last)
# Output: ['banana', 'Apple', 'date', 'Elderberry', 'cherry']

Sorting Dictionaries

python

employees = [
    {"name": "Alice", "department": "Engineering", "salary": 95000, "experience": 8},
    {"name": "Bob", "department": "Marketing", "salary": 62000, "experience": 4},
    {"name": "Charlie", "department": "Engineering", "salary": 88000, "experience": 6},
    {"name": "Diana", "department": "HR", "salary": 55000, "experience": 3},
    {"name": "Eve", "department": "Sales", "salary": 71000, "experience": 5}
]

# Sort by salary (ascending)
by_salary = sorted(employees, key=lambda e: e["salary"])
for e in by_salary:
    print(f"{e['name']}: ${e['salary']:,}")

# Output:
# Diana: $55,000
# Bob: $62,000
# Eve: $71,000
# Charlie: $88,000
# Alice: $95,000

# Sort by salary descending
by_salary_desc = sorted(employees, key=lambda e: e["salary"], reverse=True)

# Sort by department, then by salary within each department
by_dept_salary = sorted(employees, key=lambda e: (e["department"], e["salary"]))
for e in by_dept_salary:
    print(f"{e['department']} — {e['name']}: ${e['salary']:,}")

# Output:
# Engineering — Charlie: $88,000
# Engineering — Alice: $95,000
# HR — Diana: $55,000
# Marketing — Bob: $62,000
# Sales — Eve: $71,000

# Sort by multiple criteria — department ascending, salary descending
multi_sort = sorted(employees,
    key=lambda e: (e["department"], -e["salary"]))

Lambda in Pandas — Real Data Science Use Cases

Lambda functions are extensively used in pandas for transforming and filtering data.

Using apply() With Lambda

python

import pandas as pd

df = pd.DataFrame({
    'name': ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'],
    'department': ['Engineering', 'Marketing', 'Engineering', 'HR', 'Sales'],
    'salary': [95000, 62000, 88000, 55000, 71000],
    'experience': [8, 4, 6, 3, 5]
})

# Add salary band column
df['salary_band'] = df['salary'].apply(
    lambda s: 'High' if s >= 85000 else 'Medium' if s >= 65000 else 'Low'
)

# Add seniority column
df['seniority'] = df['experience'].apply(
    lambda exp: 'Senior' if exp >= 7 else 'Mid' if exp >= 5 else 'Junior'
)

# Calculate bonus column
df['bonus'] = df['salary'].apply(lambda s: s * 0.15 if s >= 85000 else s * 0.10)

# Clean name column
df['name_upper'] = df['name'].apply(lambda n: n.upper())

print(df[['name', 'salary', 'salary_band', 'seniority', 'bonus']])

Output:

namesalarysalary_bandsenioritybonus
Alice95000HighSenior14250.0
Bob62000LowJunior6200.0
Charlie88000HighMid13200.0
Diana55000LowJunior5500.0
Eve71000MediumMid7100.0

Row-Wise Lambda With apply(axis=1)

python

# Calculate total compensation using multiple columns
df['total_comp'] = df.apply(
    lambda row: row['salary'] + (row['salary'] * 0.15 if row['experience'] >= 7
                                 else row['salary'] * 0.10),
    axis=1
)

# Create performance label from multiple columns
df['performance'] = df.apply(
    lambda row: 'Star' if row['salary'] >= 85000 and row['experience'] >= 6
                else 'Solid' if row['salary'] >= 65000
                else 'Developing',
    axis=1
)

print(df[['name', 'salary', 'experience', 'performance']])

Using Lambda With map() in Pandas

python

# Map department codes to full names
dept_map = {
    'Engineering': 'ENG',
    'Marketing': 'MKT',
    'HR': 'HUM',
    'Sales': 'SAL'
}

df['dept_code'] = df['department'].map(lambda d: dept_map.get(d, 'UNK'))

# Format salary as string with currency
df['salary_formatted'] = df['salary'].map(lambda s: f"${s:,}")

print(df[['name', 'department', 'dept_code', 'salary_formatted']])

Filtering With Lambda in Pandas

python

# Filter high earners
high_earners = df[df['salary'].apply(lambda s: s >= 80000)]

# Filter using multiple conditions with lambda
senior_engineers = df[df.apply(
    lambda row: row['department'] == 'Engineering' and row['experience'] >= 6,
    axis=1
)]

print(senior_engineers[['name', 'department', 'salary', 'experience']])

Lambda vs Regular Function — When to Use Each

Full Comparison

python

# Simple operation — lambda is clean and appropriate
square = lambda x: x ** 2

# Complex operation — regular function is much better
def calculate_employee_bonus(salary, experience, performance_rating, department):
    """
    Calculate employee bonus based on multiple factors.
    Engineering department gets 20% extra on top of standard bonus.
    """
    base_bonus_rate = 0.10
    
    if performance_rating >= 9:
        base_bonus_rate = 0.20
    elif performance_rating >= 7:
        base_bonus_rate = 0.15
    
    experience_multiplier = 1 + (experience * 0.02)
    dept_multiplier = 1.20 if department == "Engineering" else 1.0
    
    bonus = salary * base_bonus_rate * experience_multiplier * dept_multiplier
    return round(bonus, 2)

When Lambda Is Appropriate

python

# As a sort key — clean and readable
employees.sort(key=lambda e: e['salary'])

# As a quick transformation in map()
salaries_with_raise = list(map(lambda s: s * 1.05, salaries))

# As a simple filter condition
active_users = list(filter(lambda u: u['active'], users))

# As a quick DataFrame transformation
df['category'] = df['score'].apply(lambda s: 'Pass' if s >= 60 else 'Fail')

When Regular Function Is Better

python

# Complex logic — use def
def categorize_customer(customer):
    # Multiple steps of logic
    if customer['purchases'] > 100 and customer['total_spend'] > 10000:
        tier = 'Platinum'
    elif customer['purchases'] > 50:
        tier = 'Gold'
    elif customer['purchases'] > 10:
        tier = 'Silver'
    else:
        tier = 'Bronze'
    
    # Additional calculations
    discount = {'Platinum': 0.20, 'Gold': 0.15, 'Silver': 0.10, 'Bronze': 0.05}
    customer['tier'] = tier
    customer['discount_rate'] = discount[tier]
    return customer

# When you need documentation
def calculate_compound_interest(principal, rate, time, n=12):
    """
    Calculate compound interest.
    
    Args:
        principal: Initial investment amount
        rate: Annual interest rate (as decimal)
        time: Time in years
        n: Compounding frequency per year (default: monthly)
    
    Returns:
        Final amount after compound interest
    """
    return principal * (1 + rate/n) ** (n * time)

# When the function is reused many times
def validate_email(email):
    import re
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return bool(re.match(pattern, email))

Common Patterns and Advanced Uses

Lambda as a Default Dictionary Value

python

from collections import defaultdict

# defaultdict with lambda as default factory
word_count = defaultdict(lambda: 0)

words = "the quick brown fox jumps over the lazy dog the fox".split()
for word in words:
    word_count[word] += 1

print(dict(sorted(word_count.items(), key=lambda x: x[1], reverse=True)))
# Output: {'the': 3, 'fox': 2, 'quick': 1, 'brown': 1, ...}

Lambda for Memoization Pattern

python

# Simple caching with lambda and dictionary
cache = {}
cached_square = lambda x: cache.setdefault(x, x ** 2)

print(cached_square(5))   # Calculates: 25
print(cached_square(5))   # From cache: 25
print(cached_square(10))  # Calculates: 100

Lambda in GUI Event Handlers

python

# In GUI frameworks like Tkinter, lambdas pass arguments to button handlers
import tkinter as tk

root = tk.Tk()

for i in range(5):
    btn = tk.Button(
        root,
        text=f"Button {i}",
        command=lambda val=i: print(f"Clicked button {val}")
    )
    btn.pack()

Chaining map, filter, and reduce

python

from functools import reduce

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

# Chain: filter evens → square them → sum the result
result = reduce(
    lambda x, y: x + y,
    map(
        lambda x: x ** 2,
        filter(lambda x: x % 2 == 0, data)
    )
)

print(result)  # Output: 220 (4 + 16 + 36 + 64 + 100)

# More readable with list comprehension (often preferred)
result_comp = sum(x ** 2 for x in data if x % 2 == 0)
print(result_comp)  # Output: 220

Lambda vs Regular Function

FeatureLambdaRegular Function (def)
SyntaxSingle lineMultiple lines
NameAnonymousNamed
ArgumentsAny numberAny number
BodySingle expressionMultiple statements
Return statementImplicit — auto-returnsExplicit return required
Docstring Not supported Supported
DebuggingHarder — no name in tracebackEasier — named in traceback
ReusabilityUsually one-time useDesigned for reuse
ReadabilityGood for simple operationsBetter for complex logic
TestingHarder to unit testEasy to unit test
Best formap, filter, sorted key, applyComplex logic, reuse, documentation

Advantages and Disadvantages of Lambda Functions

Advantages

  • Concise and compact — reduces boilerplate for simple operations
  • Convenient inline — define where you use it without a separate function definition
  • Natural fit with map(), filter(), reduce(), and sorted()
  • Clean as sort keys and pandas apply() transformations
  • Encourages functional programming style for data transformations

Disadvantages

  • Limited to a single expression — cannot contain statements, loops, or multiple lines
  • No docstrings — cannot be documented like regular functions
  • Harder to debug — lambda functions appear as <lambda> in tracebacks without a meaningful name
  • Can reduce readability if overused or made too complex
  • Not easily unit testable when not assigned to a variable

Common Mistakes to Avoid

  • Making lambda functions too complex — If your lambda spans multiple conditions and feels hard to read, it is a strong signal to switch to a regular function. Lambda should make code cleaner, not harder to understand
  • Using lambda when a list comprehension is cleanerlist(map(lambda x: x**2, numbers)) is almost always better written as [x**2 for x in numbers]. Prefer comprehensions for simple transformations
  • The late binding trap in loops — A classic Python gotcha:

python

# Wrong — all functions use the final value of i (4)
functions = [lambda: i for i in range(5)]
print([f() for f in functions])  # Output: [4, 4, 4, 4, 4]

# Correct — use default argument to capture current value
functions = [lambda i=i: i for i in range(5)]
print([f() for f in functions])  # Output: [0, 1, 2, 3, 4]
  • Assigning lambda to a variable with the same name as a built-inlist = lambda x: x shadows Python’s built-in list type. Always choose meaningful, non-conflicting names
  • Ignoring PEP 8 guidance — PEP 8 (Python’s style guide) recommends against assigning lambda functions to variables: f = lambda x: x**2. If you are assigning it to a variable, use def f(x): return x**2 instead. Lambda is meant for inline, anonymous use

Quick Reference Cheat Sheet

Use CaseLambda Pattern
Square a numberlambda x: x ** 2
Two argument additionlambda x, y: x + y
Conditionallambda x: "Yes" if x > 0 else "No"
Map — transform listlist(map(lambda x: x*2, lst))
Filter — keep matchinglist(filter(lambda x: x > 0, lst))
Reduce — aggregatereduce(lambda x, y: x + y, lst)
Sort by keysorted(lst, key=lambda x: x['salary'])
Sort descendingsorted(lst, key=lambda x: x['salary'], reverse=True)
Multi-key sortsorted(lst, key=lambda x: (x['dept'], x['salary']))
Pandas applydf['col'].apply(lambda x: x * 1.1)
Pandas row-wisedf.apply(lambda row: row['a'] + row['b'], axis=1)
Default argumentlambda x, n=10: x * n

Python lambda functions are a small but genuinely useful tool in your programming toolkit. They are not complicated once you see the pattern and they appear constantly in real Python code, especially in data science and functional programming contexts.

Here is the simplest summary of everything we covered:

  • Lambda is a way to create small, anonymous functions in a single line
  • The syntax is lambda arguments: expression — the expression is automatically returned
  • Lambda works beautifully with map(), filter(), reduce(), and sorted()
  • In pandas, lambda functions power apply() transformations across rows and columns
  • Use lambda for simple, inline, short-lived operations — switch to def for anything complex
  • Avoid lambda when a list comprehension is cleaner or when the logic needs documentation or testing

The best way to get comfortable with lambda is to start using it in the places where it fits naturally as a sort key, inside map() and filter(), and in pandas apply() calls. Once those feel natural, you will reach for lambda instinctively whenever a quick, inline function is exactly what a situation calls for.

FAQs

What is a lambda function in Python?

A lambda function is a small, anonymous function defined in a single line using the lambda keyword. It takes any number of arguments and evaluates a single expression, returning the result automatically. It is equivalent to a regular function but more compact and used inline.

When should I use lambda instead of def?

Use lambda for simple, short-lived operations especially as sort keys, in map() and filter() calls, and in pandas apply() transformations. Use def when the function has complex logic, needs documentation, will be reused in many places, or needs to be unit tested.

Can lambda functions have multiple lines?

No. Lambda functions are limited to a single expression. If you need multiple lines, statements, or complex logic, use a regular function defined with def.

What is the difference between map() and filter() with lambda?

map() applies a lambda to every element and returns the transformed results. filter() applies a lambda to every element and returns only the elements for which the lambda returns True.

Is lambda faster than a regular function in Python?

No meaningful performance difference exists between lambda and def for equivalent operations. Choose between them based on readability and appropriateness — not performance.

Can I use lambda in pandas?

Yes. Lambda functions are widely used in pandas through the apply() method for transforming columns or rows, the map() method for Series, and in sorting and filtering operations. They are one of the most common tools in data science Python workflows.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top