GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Pricing
  • Log in
  • Sign up for free
  • Full-Stack Development
  • Front-End Development
  • Back-End Development
  • Python Development
  • HTML
  • JavaScript
  • React
  • SQL
  • CSS
  • Typescript
  • Python

This view

  • Original page
  • New address

GeezerVison is showing mimo.org — Python Lambda Function: Syntax, Usage, and Examples

Coding Glossary
HTMLCSSJavaScriptPythonSwiftTypeScriptSQLReactProgramming Concepts
HTMLCSSJavaScriptPythonSwiftTypeScriptSQLReactProgramming Concepts

PYTHON

Python Lambda Function: Syntax, Usage, and Examples

A Python lambda function is a small, anonymous function that you can define in a single line. It is useful when you need a short function for a quick operation without defining it using def.

How to Use a Lambda Function in Python

The syntax of a lambda function in Python follows this structure:

Learn Python on Mimo

CAREER PATHPython Developer
Become a Python developer. Master Python from basics to advanced topics, including data structures, functions, classes, and error handling
Beginner friendly
COURSEPython
Start your coding journey with Python. Learn basics, data types, control flow, and more
Beginner friendly

Python

Open in MimoOpen in Mimo
lambda arguments: expression

  • lambda: The keyword for defining a lambda function.
  • arguments: One or more inputs, just like a regular function.
  • expression: The operation that gets evaluated and returned.

Example: Creating a Simple Lambda Function

Python

Open in MimoOpen in Mimo
square = lambda x: x * x
print(square(5))  # Output: 25

This lambda function takes x as an argument and returns its square.

When to Use a Lambda Function in Python

Lambda functions are useful when you need:

  1. Short functions that you don’t need to reuse
    • Example: Squaring numbers inside a map() function.
  2. To pass functions as arguments
    • Example: Sorting lists with custom rules.
  3. To simplify code
    • Example: Replacing short def functions with one-liners.

Examples of Lambda Functions in Python

Using Lambda with map()

map() applies a function to each element of an iterable.

Python

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

Using Lambda with filter()

filter() selects elements that match a condition.

Python

Open in MimoOpen in Mimo
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # Output: [2, 4, 6]

Using Lambda with sorted()

You can sort lists with custom sorting rules using lambda functions.

Python

Open in MimoOpen in Mimo
words = ["apple", "banana", "cherry", "blueberry"]
sorted_words = sorted(words, key=lambda word: len(word))
print(sorted_words)  # Output: ['apple', 'banana', 'cherry', 'blueberry']

Learn More About Lambda Functions in Python

Using If-Else in a Lambda Function

Lambda functions can include conditional expressions.

Python

Open in MimoOpen in Mimo
max_value = lambda a, b: a if a > b else b
print(max_value(10, 20))  # Output: 20

Passing a Lambda Function as an Argument

You can pass a lambda function to another function for flexibility.

Python

Open in MimoOpen in Mimo
def apply_operation(func, value):
    return func(value)

result = apply_operation(lambda x: x * 3, 5)
print(result)  # Output: 15

Using Lambda in a Dictionary

You can use lambda functions inside dictionaries to store different operations.

Python

Open in MimoOpen in Mimo
operations = {
    "square": lambda x: x * x,
    "double": lambda x: x * 2,
    "negate": lambda x: -x
}

print(operations["square"](5))  # Output: 25

Using Lambda with List Comprehension

You can combine lambda functions with list comprehensions for quick transformations.

Python

Open in MimoOpen in Mimo
numbers = [1, 2, 3, 4]
doubled = [(lambda x: x * 2)(n) for n in numbers]
print(doubled)  # Output: [2, 4, 6, 8]

Sorting with Lambda and Multiple Criteria

When sorting dictionaries or tuples, lambda functions help specify multiple sorting criteria.

Python

Open in MimoOpen in Mimo
students = [("Alice", 90), ("Bob", 85), ("Charlie", 85)]
sorted_students = sorted(students, key=lambda student: (-student[1], student[0]))
print(sorted_students)  # Output: [('Alice', 90), ('Bob', 85), ('Charlie', 85)]

Using Multiline Lambda Functions

By default, lambda functions in Python are limited to a single expression. However, you can work around this by using tuples or other techniques.

Python

Open in MimoOpen in Mimo
multistep = lambda x: (x * 2, x + 3, x ** 2)
print(multistep(5))  # Output: (10, 8, 25)

Assigning a Function Name to a Lambda Function

Unlike normal functions defined with the def keyword, a lambda function doesn't require an explicit function name. However, you can assign a lambda function to a variable.

Python

Open in MimoOpen in Mimo
multiply = lambda x, y: x * y  # Assigning a function name
print(multiply(3, 4))  # Output: 12

  • Unlike a normal function, this lambda function is assigned to multiply.
  • The lambda keyword makes function definitions more concise.

Data Science Use Cases

In data science, lambda functions are widely used for quick data transformations.

Python

Open in MimoOpen in Mimo
import pandas as pd

data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data)

df['Age Group'] = df['Age'].apply(lambda x: 'Young' if x < 30 else 'Adult')
print(df)

Use cases in data science include data filtering, transformations, and feature engineering.

Combining Lambda with For Loops

Although lambda functions don’t contain loops internally, they can be used inside a for loop.

Python

Open in MimoOpen in Mimo
numbers = [1, 2, 3, 4]
for num in numbers:
    print((lambda x: x * 2)(num))  # Applying lambda inside a for loop

For loops allow applying a lambda function to multiple values sequentially.

Using Lambda in Functional Programming

Python supports functional programming, where functions can be passed as arguments or returned from other functions. Higher-order functions like map(), filter(), and reduce() make lambda functions a perfect fit.

Python

Open in MimoOpen in Mimo
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, numbers))  # Functional programming
print(squared)  # Output: [1, 4, 9, 16]
  • The map() function applies the function object created by lambda to each element.
  • Higher-order functions like map() take another function as an argument.

Lambda Function vs. Regular Function

Regular functions are better when the function logic is complex, while lambda functions are ideal for simple operations.

Using a regular function:

Python

Open in MimoOpen in Mimo
def multiply(x, y):
    return x * y

print(multiply(3, 4))  # Output: 12

Using a lambda function:

Python

Open in MimoOpen in Mimo
multiply = lambda x, y: x * y
print(multiply(3, 4))  # Output: 12

Both functions do the same thing, but the lambda version is more compact.

Using Lambda to Pass a Function to a Decorator

Lambda functions can work with decorators when you need quick inline logic.

Python

Open in MimoOpen in Mimo
def decorator(func):
    return lambda x: func(x) + 1

@decorator
def square(x):
    return x * x

print(square(4))  # Output: 17 (4*4 + 1)

Formatting Strings with Lambda Functions

You can format strings using lambda functions for dynamic output.

Python

Open in MimoOpen in Mimo
format_string = lambda name, age: f"My name is {name} and I am {age} years old."
print(format_string("Alice", 30))
# Output: My name is Alice and I am 30 years old.

Best Practices for Lambda Functions

  • Use lambda functions for simple, one-time operations.
  • Prefer regular functions when logic requires multiple statements.
  • Use lambda functions inside map, filter, sorted, and other built-in functions.
  • Avoid writing long, complex lambda expressions that reduce readability.

Python lambda functions offer a quick way to define short, throwaway functions without writing a full function definition. Lambda functions make your code more concise, whether you're filtering data, transforming values, or passing functions as arguments.

Join 40M+ people learning for free on Mimo

Person 1
Person 2
Person 3
40M+
CAREER PATHPython Developer
Become a Python developer. Master Python from basics to advanced topics, including data structures, functions, classes, and error handling
Beginner friendly
COURSEPython
Start your coding journey with Python. Learn basics, data types, control flow, and more
Beginner friendly

4.8 out of 5 across 1M+ reviews

Check us out on Apple AppStore, Google Play Store, and Trustpilot

  • What is Python?
  • __init__() function
  • *args and **kwargs
  • Aliases
  • and operator
  • any() function
  • argparse
  • Arrays
  • asyncio
  • Booleans
  • Break statement
  • Bytes
  • Classes
  • Closure
  • Code blocks
  • Comments
  • Conditional statements
  • Console
  • Context manager
  • Data class
  • Data structures
  • Data types
  • Data visualization
  • datetime module
  • Decorator
  • Dictionaries
  • Dictionary comprehension
  • Django
  • Docstrings
  • Dunder methods
  • Encapsulation
  • enum
  • enumerate() function
  • Equality operator
  • Error handling
  • Exception handling
  • False
  • File handling
  • Filter()
  • Flask framework
  • Floats
  • Floor division
  • For loops
  • Formatted strings
  • Functions
  • Generator
  • Globals()
  • Greater than operator
  • Greater than or equal to operator
  • If statement
  • in operator
  • Indices
  • Inequality operator
  • Inheritance
  • Integers
  • Iterator
  • JSON
  • Lambda function
  • len() Function
  • Less than operator
  • Less than or equal to operator
  • List append() method
  • List comprehension
  • List count()
  • List insert() method
  • List pop() method
  • List reverse() method
  • List sort() method
  • Lists
  • Logging
  • map() function
  • Match statement
  • Math module
  • Merge sort
  • Min()
  • Modules
  • Modulo operator
  • Multiline comment
  • Multiprocessing
  • Multithreading
  • Nested loops
  • None
  • not operator
  • NumPy library
  • OOP
  • Optional arguments
  • or operator
  • Override method
  • Package manager (pip)
  • Packages
  • Pandas library
  • Parameters
  • pathlib module
  • Pickle
  • Polymorphism
  • print() function
  • Property()
  • Protocol
  • Random module
  • range() function
  • Raw strings
  • Recursion
  • Reduce()
  • Regular expressions
  • requests Library
  • return statement
  • round() function
  • Script
  • Set comprehension
  • Sets
  • SQLite
  • String decode()
  • String find()
  • String join() method
  • String replace() method
  • String split() method
  • String strip()
  • Strings
  • Ternary operator
  • time.sleep() function
  • True
  • try...except statement
  • Tuples
  • Type casting
  • Type hints
  • uuid module
  • Variables
  • Virtual environment
  • While loops
  • yield
  • Zip function

You can code, too.

Company

Careers

Blog

Jobs

Product

App

Courses

Certifications

Glossary

Code Compilers

Building Experience

Useful

Press Kit

Imprint

Help

Terms of Use

Privacy Policy

Follow us

© 2026 Mimo GmbH

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.